A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
If you have further questions related to development or usage, join us: ruby-jwt google group.
See CHANGELOG.md for a complete set of changes and upgrade guide for upgrading between major versions.
| Logo | Message |
|---|---|
| If you want to quickly add secure token-based authentication to Ruby projects, feel free to check Auth0's Ruby SDK and free plan at auth0.com/developers |
gem install jwtAdd the following to your Gemfile
gem 'jwt'And run bundle install
Finally require the gem in your application
require 'jwt'The jwt gem natively supports the NONE, HMAC, RSASSA, ECDSA and RSASSA-PSS algorithms via the openssl library. The gem can be extended with additional or alternative implementations of the algorithms via extensions.
Additionally the EdDSA algorithm is supported via a the jwt-eddsa gem.
For safe cryptographic signing, you need to specify the algorithm in the options hash whenever you call JWT.decode to ensure that an attacker cannot bypass the algorithm verification step. It is strongly recommended that you hard code the algorithm, as you may leave yourself vulnerable by dynamically picking the algorithm
See JSON Web Algorithms (JWA) 3.1. "alg" (Algorithm) Header Parameter Values for JWS
payload = { data: 'test' }
token = JWT.encode(payload, nil, 'none')
# => "eyJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9."
decoded_token = JWT.decode(token, nil, true, { algorithm: 'none' })
# => [
# {"data"=>"test"}, # payload
# {"alg"=>"none"} # header
# ]payload = { data: 'test' }
hmac_secret = 'my$ecretK3y'
token = JWT.encode(payload, hmac_secret, 'HS256')
# => "eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pNIWIL34Jo13LViZAJACzK6Yf0qnvT_BuwOxiMCPE-Y"
decoded_token = JWT.decode(token, hmac_secret, true, { algorithm: 'HS256' })
# => [
# {"data"=>"test"}, # payload
# {"alg"=>"HS256"} # header
# ]payload = { data: 'test' }
rsa_private = OpenSSL::PKey::RSA.generate(2048)
rsa_public = rsa_private.public_key
token = JWT.encode(payload, rsa_private, 'RS256')
# => "eyJhbGciOiJSUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.CCkO35qFPijW8Gwhbt8a80PB9fc9FJ19hCMnXSgoDF6Mlvlt0A4G-ah..."
decoded_token = JWT.decode(token, rsa_public, true, { algorithm: 'RS256' })
# => [
# {"data"=>"test"}, # payload
# {"alg"=>"RS256"} # header
# ]payload = { data: 'test' }
ecdsa_key = OpenSSL::PKey::EC.generate('prime256v1')
token = JWT.encode(payload, ecdsa_key, 'ES256')
# => "eyJhbGciOiJFUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.AlLW--kaF7EX1NMX9WJRuIW8NeRJbn2BLXHns7Q5TZr7Hy3lF6MOpMlp7GoxBFRLISQ6KrD0CJOrR8aogEsPeg"
decoded_token = JWT.decode(token, ecdsa_key, true, { algorithm: 'ES256' })
# => [
# {"test"=>"data"}, # payload
# {"alg"=>"ES256"} # header
# ]Since version 3.0, the EdDSA algorithm has been moved to the jwt-eddsa gem.
payload = { data: 'test' }
rsa_private = OpenSSL::PKey::RSA.generate(2048)
rsa_public = rsa_private.public_key
token = JWT.encode(payload, rsa_private, 'PS256')
# => "eyJhbGciOiJQUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.BRWizdUjD5zAWw-EDBcrl3dDpQDAePz9Ol3XKC43SggU47G8OWwveA_..."
decoded_token = JWT.decode(token, rsa_public, true, { algorithm: 'PS256' })
# => [
# {"data"=>"test"}, # payload
# {"alg"=>"PS256"} # header
# ]When encoding or decoding a token, you can pass in a custom object through the algorithm option to handle signing or verification. This custom object must include or extend the JWT::JWA::SigningAlgorithm module and implement certain methods:
alg and verify.alg and sign.For customization options check the details from JWT::JWA::SigningAlgorithm.
…The ruby-jwt gem supports custom header fields
To add custom header fields you need to pass header_fields parameter
payload = { data: 'test' }
token = JWT.encode(payload, nil, 'none', { typ: 'JWT' })
# => "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9."
decoded_token = JWT.decode(token, nil, true, { algorithm: 'none' })
# => [
# {"data"=>"test"}, # payload
# {"typ"=>"JWT", "alg"=>"none"} # header
# ]JWT::Token and JWT::EncodedTokenThe JWT::Token and JWT::EncodedToken classes can be used to manage your JWTs.
payload = { exp: Time.now.to_i + 60, jti: '1234', sub: "my-subject" }
header = { kid: 'hmac' }
token = JWT::Token.new(payload: payload, header: header)
token.sign!(algorithm: 'HS256', key: "secret")
token.jwt
# => "eyJraWQiOiJobWFjIiwiYWxnIjoiSFMyNTYifQ.eyJleHAiOjE3NTAwMDU0NzksImp0aSI6IjEyMzQiLCJzdWIiOiJteS1zdWJqZWN0In0.NRLcK6fYr3IdNfmncJePMWLQ34M4n14EgqSYrQIjL9w"The JWT::EncodedToken can be used as a token object that allows verification of signatures and claims.
…The JWT::EncodedToken#verify! method can be used to verify signature and claim verification in one go. The exp claim is verified by default.
encoded_token = JWT::EncodedToken.new(token.jwt)
encoded_token.verify!(signature: {algorithm: 'HS256', key: "secret"})
encoded_token.payload # => { 'exp'=>1234, 'jti'=>'1234", 'sub'=>'my-subject' }
encoded_token.header # {'kid'=>'hmac', 'alg'=>'HS256'}A JWK can be used to sign and verify the token if it's possible to derive the signing algorithm from the key.
jwk_json = '{
"kty": "oct",
"k": "c2VjcmV0",
"alg": "HS256",
"kid": "hmac"
}'
jwk = JWT::JWK.import(JSON.parse(jwk_json))
token = JWT::Token.new(payload: payload, header: header)
token.sign!(key: jwk, algorithm: 'HS256')
encoded_token = JWT::EncodedToken.new(token.jwt)
encoded_token.verify!(signature: { algorithm: ["HS256", "HS512"], key: jwk})A keyfinder can be used to verify a signature. A keyfinder is an object responding to the #call method. The method expects to receive one argument, which is the token to be verified.
An example on using the built-in JWK keyfinder.
# Create and sign a token
jwk = JWT::JWK.new(OpenSSL::PKey::RSA.generate(2048))
token = JWT::Token.new(payload: { pay: 'load' }, header: { kid: jwk.kid })
token.sign!(algorithm: 'RS256', key: jwk.signing_key)
# Create keyfinder object, verify and decode token
key_finder = JWT::JWK::KeyFinder.new(jwks: JWT::JWK::Set.new(jwk))
encoded_token = JWT::EncodedToken.new(token.jwt)
encoded_token.verify!(signature: { algorithm: 'RS256', key_finder: key_finder})
encoded_token.payload # => { 'pay' => 'load' }Using a custom keyfinder proc.
# Create and sign a token
key = OpenSSL::PKey::RSA.generate(2048)
token = JWT::Token.new(payload: { pay: 'load' })
token.sign!(algorithm: 'RS256', key: key)
# Verify and decode token
encoded_token = JWT::EncodedToken.new(token.jwt)
encoded_token.verify!(signature: { algorithm: 'RS256', key_finder: ->(_token){ key.public_key }})
encoded_token.payload # => { 'pay' => 'load' }The ::JWT::Token#detach_payload! method can be use to detach the payload from the JWT.
token = JWT::Token.new(payload: { pay: 'load' })
token.sign!(algorithm: 'HS256', key: "secret")
token.detach_payload!
token.jwt # => "eyJhbGciOiJIUzI1NiJ9..UEhDY1Qlj29ammxuVRA_-gBah4qTy5FngIWg0yEAlC0"
token.encoded_payload # => "eyJwYXkiOiJsb2FkIn0"The JWT::EncodedToken class can be used to decode a token with a detached payload by providing the payload to the token instance in separate.
encoded_token = JWT::EncodedToken.new(token.jwt)
encoded_token.encoded_payload = "eyJwYXkiOiJsb2FkIn0"
encoded_token.verify_signature!(algorithm: 'HS256', key: "secret")
encoded_token.payload # => {"pay"=>"load"}JSON Web Token defines some reserved claim names and defines how they should be used. JWT supports these reserved claim names:
From Oauth JSON Web Token 4.1.4. "exp" (Expiration Time) Claim:
The
exp(expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of theexpclaim requires that the current date/time MUST be before the expiration date/time listed in theexpclaim. Implementers MAY provide for some smallleeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
exp = Time.now.to_i + 4 * 3600
exp_payload = { data: 'data', exp: exp }
token = JWT.encode(exp_payload, hmac_secret, 'HS256')
begin
decoded_token = JWT.decode(token, hmac_secret, true, { algorithm: 'HS256' })
rescue JWT::ExpiredSignature
# Handle expired token, e.g. logout user or deny access
endThe Expiration Claim verification can be disabled.
# Decode token without raising JWT::ExpiredSignature error
JWT.decode(token, hmac_secret, true, { verify_expiration: false, algorithm: 'HS256' })Leeway and the exp claim.
exp = Time.now.to_i - 10
leeway = 30 # seconds
exp_payload = { data: 'data', exp: exp }
# build expired token
token = JWT.encode(exp_payload, hmac_secret, 'HS256')
begin
# add leeway to ensure the token is still accepted
decoded_token = JWT.decode(token, hmac_secret, true, { exp_leeway: leeway, algorithm: 'HS256' })
rescue JWT::ExpiredSignature
# Handle expired token, e.g. logout user or deny access
endFrom [Oauth JSON Web Token 4.1.5. "nbf" (Not Before
No open issues yet, or sync has not completed.