Module: RackJwtVerifier::Scopes

Defined in:
lib/rack_jwt_verifier/scopes.rb

Overview

Reads the scopes granted by a verified token.

Two claim shapes are understood: scopes, an Array of Strings (what jwt_auth_client emits), and scope, a space-delimited String (the OAuth 2 convention, RFC 8693 §4.2 / RFC 9068 §2.2.3). Both are normalised to an Array of Strings.

claims = env["rack_jwt_verifier.payload"]
RackJwtVerifier::Scopes.from(claims)                     # => ["read:invoices"]
RackJwtVerifier::Scopes.include?(claims, "read:invoices") # => true
RackJwtVerifier::Scopes.missing(claims, %w[read:x write:x]) # => ["write:x"]

Class Method Summary collapse

Class Method Details

.from(payload) ⇒ Array<String>

Returns granted scopes; empty when there are none.

Parameters:

  • payload (Hash, nil)

    the verified claims.

Returns:

  • (Array<String>)

    granted scopes; empty when there are none.



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rack_jwt_verifier/scopes.rb', line 20

def from(payload)
  return [] unless payload.is_a?(Hash)

  raw = payload["scopes"] || payload[:scopes]
  raw = payload["scope"] || payload[:scope] if raw.nil?

  case raw
  when Array then raw.map(&:to_s).reject(&:empty?)
  when String then raw.split
  else []
  end
end

.include?(payload, *scopes) ⇒ Boolean

Returns true when every given scope is granted.

Returns:

  • (Boolean)

    true when every given scope is granted.



39
40
41
# File 'lib/rack_jwt_verifier/scopes.rb', line 39

def include?(payload, *scopes)
  missing(payload, scopes.flatten).empty?
end

.missing(payload, required) ⇒ Array<String>

Returns the required scopes the payload does not grant.

Returns:

  • (Array<String>)

    the required scopes the payload does not grant.



34
35
36
# File 'lib/rack_jwt_verifier/scopes.rb', line 34

def missing(payload, required)
  Array(required).map(&:to_s) - from(payload)
end