Class: Stytch::M2M
Defined Under Namespace
Classes: Clients
Instance Attribute Summary collapse
-
#clients ⇒ Object
readonly
Returns the value of attribute clients.
Instance Method Summary collapse
-
#authenticate_token(access_token:, required_scopes: nil, max_token_age: nil, scope_authorization_func: method(:perform_authorization_check), clock_tolerance_seconds: nil) ⇒ Object
MANUAL(M2M::authenticate_token)(SERVICE_METHOD)
authenticate_tokenvalidates a M2M JWT locally. -
#authenticate_token_local(jwt, clock_tolerance_seconds: nil) ⇒ Object
Parse a M2M token and verify the signature locally (without calling /authenticate in the API) If clock_tolerance_seconds is not supplied 0 seconds will be used as the default.
-
#get_jwks(project_id:) ⇒ Object
MANUAL(M2M::get_jwks)(SERVICE_METHOD) This is a helper so we can retrieve the JWKS for a project for decoding M2M access tokens.
-
#initialize(connection, project_id, is_b2b_client, jwks_cache) ⇒ M2M
constructor
A new instance of M2M.
- #marshal_jwt_into_response(jwt) ⇒ Object
-
#perform_authorization_check(has_scopes:, required_scopes:) ⇒ Object
Performs an authorization check against an M2M client and a set of required scopes.
-
#token(client_id:, client_secret:, scopes: nil) ⇒ Object
MANUAL(M2M::token)(SERVICE_METHOD)
tokenretrieves an access token for the given M2M Client.
Methods included from RequestHelper
#delete_request, #get_request, #post_request, #put_request, #request_with_query_params
Constructor Details
#initialize(connection, project_id, is_b2b_client, jwks_cache) ⇒ M2M
Returns a new instance of M2M.
16 17 18 19 20 21 22 23 |
# File 'lib/stytch/m2m.rb', line 16 def initialize(connection, project_id, is_b2b_client, jwks_cache) @connection = connection @clients = Stytch::M2M::Clients.new(@connection) @project_id = project_id @jwks_cache = jwks_cache @is_b2b_client = is_b2b_client end |
Instance Attribute Details
#clients ⇒ Object (readonly)
Returns the value of attribute clients.
14 15 16 |
# File 'lib/stytch/m2m.rb', line 14 def clients @clients end |
Instance Method Details
#authenticate_token(access_token:, required_scopes: nil, max_token_age: nil, scope_authorization_func: method(:perform_authorization_check), clock_tolerance_seconds: nil) ⇒ Object
MANUAL(M2M::authenticate_token)(SERVICE_METHOD) authenticate_token validates a M2M JWT locally.
Parameters:
- access_token
-
The access token granted to the client. Access tokens are JWTs signed with the project’s JWKs. The type of this field is
String. - required_scopes
-
A list of scopes the token must have to be valid. The type of this field is nilable list of
String. - max_token_age
-
The maximum possible lifetime in seconds for the token to be valid. The type of this field is nilable
Integer. - scope_authorization_func
-
A function to check if the token has the required scopes. This defaults to a function that assumes scopes are either direct string matches or written in the form “action:resource”. See the documentation for
perform_authorization_checkfor more information.
clock_tolerance_seconds:
The tolerance to use during verification of the nbf claim. This can help with clock drift issues.
The type of this field is nilable +Integer+.
Returns:
nil if the token could not be validated, or an object with the following fields:
- scopes
-
An array of scopes granted to the token holder. The type of this field is list of
String. - client_id
-
The ID of the client that was issued the token The type of this field is
String. - custom_claims
-
A map of custom claims present in the token. The type of this field is
object.
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/stytch/m2m.rb', line 110 def authenticate_token( access_token:, required_scopes: nil, max_token_age: nil, scope_authorization_func: method(:perform_authorization_check), clock_tolerance_seconds: nil ) # Intentionally allow this to re-raise if authentication fails decoded_jwt = authenticate_token_local(access_token, clock_tolerance_seconds: clock_tolerance_seconds) iat_time = Time.at(decoded_jwt['iat']).to_datetime # Token too old raise JWTExpiredError if !max_token_age.nil? && (iat_time + max_token_age < Time.now) resp = marshal_jwt_into_response(decoded_jwt) unless required_scopes.nil? = .call( has_scopes: resp['scopes'], required_scopes: required_scopes ) raise M2MPermissionError.new(resp['scopes'], required_scopes) unless end resp end |
#authenticate_token_local(jwt, clock_tolerance_seconds: nil) ⇒ Object
Parse a M2M token and verify the signature locally (without calling /authenticate in the API) If clock_tolerance_seconds is not supplied 0 seconds will be used as the default.
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/stytch/m2m.rb', line 174 def authenticate_token_local(jwt, clock_tolerance_seconds: nil) clock_tolerance_seconds = 0 if clock_tolerance_seconds.nil? default_issuer = 'stytch.com/' + @project_id base_url_issuer = @connection.url_prefix valid_issuers = [default_issuer, base_url_issuer] begin decoded_token = JWT.decode jwt, nil, true, { jwks: @jwks_cache.loader, iss: valid_issuers, verify_iss: true, aud: @project_id, verify_aud: true, algorithms: ['RS256'], nbf_leeway: clock_tolerance_seconds } decoded_token[0] rescue JWT::InvalidIssuerError raise JWTInvalidIssuerError rescue JWT::InvalidAudError raise JWTInvalidAudienceError rescue JWT::ExpiredSignature raise JWTExpiredSignatureError rescue JWT::IncorrectAlgorithm raise JWTIncorrectAlgorithmError end end |
#get_jwks(project_id:) ⇒ Object
MANUAL(M2M::get_jwks)(SERVICE_METHOD) This is a helper so we can retrieve the JWKS for a project for decoding M2M access tokens
27 28 29 30 31 32 33 34 35 |
# File 'lib/stytch/m2m.rb', line 27 def get_jwks( project_id: ) headers = {} query_params = {} path = @is_b2b_client ? "/v1/b2b/sessions/jwks/#{project_id}" : "/v1/sessions/jwks/#{project_id}" request = request_with_query_params(path, query_params) get_request(request, headers) end |
#marshal_jwt_into_response(jwt) ⇒ Object
195 196 197 198 199 200 201 202 203 204 205 206 |
# File 'lib/stytch/m2m.rb', line 195 def marshal_jwt_into_response(jwt) # The custom claim set is all the claims in the payload except for the standard claims. # The cleanest way to collect those seems to be naming what we want # to omit and filtering the rest to collect the custom claims. reserved_claims = %w[aud exp iat iss jti nbf sub] custom_claims = jwt.reject { |key, _| reserved_claims.include?(key) } { 'scopes' => jwt['scope'].split(' '), 'client_id' => jwt['sub'], 'custom_claims' => custom_claims } end |
#perform_authorization_check(has_scopes:, required_scopes:) ⇒ Object
Performs an authorization check against an M2M client and a set of required scopes. Returns true if the client has all the required scopes, false otherwise. A scope can match if the client has a wildcard resource or the specific resource. This function assumes that scopes are of the form “action:resource” or just “specific_scope”. It is also possible to represent scopes as “resource:action”, but it is ultimately up to the developer to ensure consistency in the scopes format. Note that a scope of “*” will only match another literal “*” because wildcards are not supported in the prefix piece of a scope.
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
# File 'lib/stytch/m2m.rb', line 146 def ( has_scopes:, required_scopes: ) client_scopes = Hash.new { |hash, key| hash[key] = Set.new } has_scopes.each do |scope| action = scope resource = '-' action, resource = scope.split(':') if scope.include?(':') client_scopes[action].add(resource) end required_scopes.each do |required_scope| required_action = required_scope required_resource = '-' required_action, required_resource = required_scope.split(':') if required_scope.include?(':') return false unless client_scopes.key?(required_action) resources = client_scopes[required_action] # The client can either have a wildcard resource or the specific resource return false unless resources.include?('*') || resources.include?(required_resource) end true end |
#token(client_id:, client_secret:, scopes: nil) ⇒ Object
MANUAL(M2M::token)(SERVICE_METHOD) token retrieves an access token for the given M2M Client. Access tokens are JWTs signed with the project’s JWKs, and are valid for one hour after issuance. M2M Access tokens contain a standard set of claims as well as any custom claims generated from templates.
Parameters:
- client_id
-
The ID of the client. The type of this field is
String. - client_secret
-
The secret of the client. The type of this field is
String. - scopes
-
An array scopes requested. If omitted, all scopes assigned to the client will be returned. The type of this field is nilable list of
String.
Returns:
An object with the following fields:
- access_token
-
The access token granted to the client. Access tokens are JWTs signed with the project’s JWKs. The type of this field is
String. - expires_in
-
The lifetime in seconds of the access token. For example, the value 3600 denotes that the access token will expire in one hour from the time the response was generated. The type of this field is
Integer. - token_type
-
The type of the returned access token. Today, this value will always be equal to “bearer” The type of this field is
String.
66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/stytch/m2m.rb', line 66 def token(client_id:, client_secret:, scopes: nil) headers = {} request = { grant_type: 'client_credentials', client_id: client_id, client_secret: client_secret } request[:scope] = scopes.join(' ') unless scopes.nil? post_request("/v1/public/#{@project_id}/oauth2/token", request, headers) end |