Skip to content

Commit a31fe87

Browse files
committed
Handle invalid token when adding redirection headers
1 parent 49e2fb5 commit a31fe87

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

lib/shopify_app/controller_concerns/login_protection.rb

+11-7
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,7 @@ def add_top_level_redirection_headers(url: nil, ignore_response_code: false)
8585
# Make sure the shop is set in the redirection URL
8686
unless params[:shop]
8787
ShopifyApp::Logger.debug("Setting current shop session")
88-
params[:shop] = if current_shopify_session
89-
current_shopify_session.shop
90-
91-
elsif shopify_id_token
92-
jwt_payload = ShopifyAPI::Auth::JwtPayload.new(shopify_id_token)
93-
jwt_payload.shop
94-
end
88+
params[:shop] = current_shopify_session&.shop || parse_shop_from_jwt
9589
end
9690

9791
url ||= login_url_with_optional_shop
@@ -279,5 +273,15 @@ def requested_by_javascript?
279273
request.media_type == "text/javascript" ||
280274
request.media_type == "application/javascript"
281275
end
276+
277+
def parse_shop_from_jwt
278+
return nil unless shopify_id_token
279+
280+
jwt_payload = ShopifyAPI::Auth::JwtPayload.new(shopify_id_token)
281+
jwt_payload.shop
282+
rescue ShopifyAPI::Errors::InvalidJwtTokenError
283+
ShopifyApp::Logger.warn("Invalid JWT token for current Shopify session")
284+
nil
285+
end
282286
end
283287
end

test/shopify_app/controller_concerns/login_protection_test.rb

+14
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,20 @@ class LoginProtectionControllerTest < ActionController::TestCase
446446
end
447447
end
448448

449+
test "#activate_shopify_session when not enough scope and rescuing from invalid JWT token, breaks out of iframe in XHR requests" do
450+
ShopifyAPI::Context.stubs(:scope).returns(ShopifyAPI::Auth::AuthScopes.new(["scope1", "scope2"]))
451+
ShopifyAPI::Utils::SessionUtils.stubs(:current_session_id).returns(nil)
452+
453+
cookies.encrypted[ShopifyAPI::Auth::Oauth::SessionCookie::SESSION_COOKIE_NAME] = "cookie"
454+
request.headers["HTTP_AUTHORIZATION"] = "Bearer token"
455+
456+
with_application_test_routes do
457+
get :index, xhr: true
458+
459+
assert_equal "/login", response.headers["X-Shopify-API-Request-Failure-Reauthorize-Url"]
460+
end
461+
end
462+
449463
test "#activate_shopify_session when rescuing from non 401 errors, does not close session" do
450464
with_application_test_routes do
451465
cookies.encrypted[ShopifyAPI::Auth::Oauth::SessionCookie::SESSION_COOKIE_NAME] = "cookie"

0 commit comments

Comments
 (0)