Module: ShopifyAPI::Auth::TokenExchange

Extended by:
T::Sig
Defined in:
lib/shopify_api/auth/token_exchange.rb

Defined Under Namespace

Classes: RequestedTokenType

Constant Summary collapse

TOKEN_EXCHANGE_GRANT_TYPE =
"urn:ietf:params:oauth:grant-type:token-exchange"
ID_TOKEN_TYPE =
"urn:ietf:params:oauth:token-type:id_token"

Class Method Summary collapse

Class Method Details

.exchange_token(session_token:, requested_token_type:, shop: nil) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/shopify_api/auth/token_exchange.rb', line 29

def exchange_token(session_token:, requested_token_type:, shop: nil)
  unless ShopifyAPI::Context.setup?
    raise ShopifyAPI::Errors::ContextNotSetupError,
      "ShopifyAPI::Context not setup, please call ShopifyAPI::Context.setup"
  end
  raise ShopifyAPI::Errors::UnsupportedOauthError,
    "Cannot perform OAuth Token Exchange for private apps." if ShopifyAPI::Context.private?
  raise ShopifyAPI::Errors::UnsupportedOauthError,
    "Cannot perform OAuth Token Exchange for non embedded apps." unless ShopifyAPI::Context.embedded?

  # Validate the session token and use the shop from the token's `dest` claim
  jwt_payload = ShopifyAPI::Auth::JwtPayload.new(session_token)
  dest_shop = jwt_payload.shop

  if shop
    ShopifyAPI::Logger.deprecated(
      "The `shop` parameter for `exchange_token` is deprecated and will be removed in v17. " \
        "The shop is now always taken from the session token's `dest` claim.",
      "17.0.0",
    )
  end

  shop_session = ShopifyAPI::Auth::Session.new(shop: dest_shop)
  body = {
    client_id: ShopifyAPI::Context.api_key,
    client_secret: ShopifyAPI::Context.api_secret_key,
    grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
    subject_token: session_token,
    subject_token_type: ID_TOKEN_TYPE,
    requested_token_type: requested_token_type.serialize,
  }

  if requested_token_type == RequestedTokenType::OFFLINE_ACCESS_TOKEN
    body.merge!({ expiring: ShopifyAPI::Context.expiring_offline_access_tokens ? 1 : 0 })
  end

  client = Clients::HttpClient.new(session: shop_session, base_path: "/admin/oauth")
  response = begin
    client.request(
      Clients::HttpRequest.new(
        http_method: :post,
        path: "access_token",
        body: body,
        body_type: "application/json",
      ),
    )
  rescue ShopifyAPI::Errors::HttpResponseError => error
    if error.code == 400 && error.response.body["error"] == "invalid_subject_token"
      raise ShopifyAPI::Errors::InvalidJwtTokenError, "Session token was rejected by token exchange"
    end

    raise error
  end

  session_params = T.cast(response.body, T::Hash[String, T.untyped]).to_h

  Session.from(
    shop: dest_shop,
    access_token_response: Oauth::AccessTokenResponse.from_hash(session_params),
  )
end

.migrate_to_expiring_token(shop:, non_expiring_offline_token:) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/shopify_api/auth/token_exchange.rb', line 97

def migrate_to_expiring_token(shop:, non_expiring_offline_token:)
  unless ShopifyAPI::Context.setup?
    raise ShopifyAPI::Errors::ContextNotSetupError,
      "ShopifyAPI::Context not setup, please call ShopifyAPI::Context.setup"
  end

  validated_shop = Utils::ShopValidator.sanitize!(shop)
  shop_session = ShopifyAPI::Auth::Session.new(shop: validated_shop)
  body = {
    client_id: ShopifyAPI::Context.api_key,
    client_secret: ShopifyAPI::Context.api_secret_key,
    grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
    subject_token: non_expiring_offline_token,
    subject_token_type: RequestedTokenType::OFFLINE_ACCESS_TOKEN.serialize,
    requested_token_type: RequestedTokenType::OFFLINE_ACCESS_TOKEN.serialize,
    expiring: "1",
  }

  client = Clients::HttpClient.new(session: shop_session, base_path: "/admin/oauth")
  response = begin
    client.request(
      Clients::HttpRequest.new(
        http_method: :post,
        path: "access_token",
        body: body,
        body_type: "application/json",
      ),
    )
  rescue ShopifyAPI::Errors::HttpResponseError => error
    ShopifyAPI::Context.logger.debug("Failed to migrate to expiring offline token: #{error.message}")
    raise error
  end

  session_params = T.cast(response.body, T::Hash[String, T.untyped]).to_h

  Session.from(
    shop: validated_shop,
    access_token_response: Oauth::AccessTokenResponse.from_hash(session_params),
  )
end