Class: JWT::Rack::Token
- Inherits:
-
Object
- Object
- JWT::Rack::Token
- Defined in:
- lib/jwt/rack/token.rb
Overview
Token encoding and decoding
Constant Summary collapse
- TOKEN_REGEX =
abc123.abc123.abc123 (w/ signature) abc123.abc123. (‘none’)
/\A([a-zA-Z0-9\-\_\~\+\\]+\.[a-zA-Z0-9\-\_\~\+\\]+\.[a-zA-Z0-9\-\_\~\+\\]*)\z/.freeze
- DEFAULT_HEADERS =
{ typ: 'JWT' }.freeze
Class Method Summary collapse
- .decode(token, secret, verify, options = {}) ⇒ Object
- .encode(payload, secret, alg = 'HS256') ⇒ Object
- .secret_of_valid_type?(secret) ⇒ Boolean
Class Method Details
.decode(token, secret, verify, options = {}) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/jwt/rack/token.rb', line 26 def self.decode(token, secret, verify, = {}) raise 'Invalid token format.' unless valid_token_format?(token) raise 'Invalid secret type.' unless secret_of_valid_type?(secret) raise 'Unsupported verify value.' unless verify_of_valid_type?(verify) [:algorithm] = 'HS256' if [:algorithm].nil? raise 'Unsupported algorithm' unless algorithm_supported?([:algorithm]) # If using an unsigned 'none' algorithm token you *must* set the # `secret` to `nil` and `verify` to `false` or it won't work per # the ruby-jwt docs. Using 'none' is probably not recommended. if [:algorithm] == 'none' ::JWT.decode(token, nil, false, ) else ::JWT.decode(token, secret, verify, ) end end |
.encode(payload, secret, alg = 'HS256') ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/jwt/rack/token.rb', line 12 def self.encode(payload, secret, alg = 'HS256') raise 'Invalid payload. Must be a Hash.' unless payload.is_a?(Hash) raise 'Invalid secret type.' unless secret_of_valid_type?(secret) raise 'Unsupported algorithm' unless algorithm_supported?(alg) # if using an unsigned token ('none' alg) you *must* set the `secret` # to `nil` in which case any user provided `secret` will be ignored. if alg == 'none' ::JWT.encode(payload, nil, alg, DEFAULT_HEADERS) else ::JWT.encode(payload, secret, alg, DEFAULT_HEADERS) end end |
.secret_of_valid_type?(secret) ⇒ Boolean
44 45 46 47 48 49 50 51 |
# File 'lib/jwt/rack/token.rb', line 44 def self.secret_of_valid_type?(secret) secret.nil? || secret.is_a?(String) || secret.is_a?(OpenSSL::PKey::RSA) || secret.is_a?(OpenSSL::PKey::EC) || (defined?(RbNaCl) && secret.is_a?(RbNaCl::Signatures::Ed25519::SigningKey)) || (defined?(RbNaCl) && secret.is_a?(RbNaCl::Signatures::Ed25519::VerifyKey)) end |