Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

ruby-jwt

> 安全
Open source

A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.

3.7K stars0 likes1 views
WebsiteGitHub

About

A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.

JWT

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.

Sponsors

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

Installing

Using Rubygems

bash
gem install jwt

Using Bundler

Add the following to your Gemfile

bash
gem 'jwt'

And run bundle install

Finally require the gem in your application

ruby
require 'jwt'

Algorithms and Usage

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

NONE

  • none - unsigned token
ruby
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
#     ]

HMAC

  • HS256 - HMAC using SHA-256 hash algorithm
  • HS384 - HMAC using SHA-384 hash algorithm
  • HS512 - HMAC using SHA-512 hash algorithm
ruby
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
#    ]

RSA

  • RS256 - RSA using SHA-256 hash algorithm
  • RS384 - RSA using SHA-384 hash algorithm
  • RS512 - RSA using SHA-512 hash algorithm
ruby
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
#    ]

ECDSA

  • ES256 - ECDSA using P-256 and SHA-256
  • ES384 - ECDSA using P-384 and SHA-384
  • ES512 - ECDSA using P-521 and SHA-512
  • ES256K - ECDSA using P-256K and SHA-256
ruby
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
#    ]

EdDSA

Since version 3.0, the EdDSA algorithm has been moved to the jwt-eddsa gem.

RSASSA-PSS

  • PS256 - RSASSA-PSS using SHA-256 hash algorithm
  • PS384 - RSASSA-PSS using SHA-384 hash algorithm
  • PS512 - RSASSA-PSS using SHA-512 hash algorithm
ruby
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
#    ]

Custom algorithms

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:

  • For decoding/verifying: The object must implement the methods alg and verify.
  • For encoding/signing: The object must implement the methods alg and sign.

For customization options check the details from JWT::JWA::SigningAlgorithm.

…

Add custom header fields

The ruby-jwt gem supports custom header fields To add custom header fields you need to pass header_fields parameter

ruby
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::EncodedToken

The JWT::Token and JWT::EncodedToken classes can be used to manage your JWTs.

Signing and encoding a token

ruby
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"

Verifying and decoding a token

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.

ruby
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.

ruby
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})

Using a keyfinder

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.

ruby
# 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.

ruby
# 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' }

Detached payload

The ::JWT::Token#detach_payload! method can be use to detach the payload from the JWT.

ruby
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.

ruby
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"}

Claims

JSON Web Token defines some reserved claim names and defines how they should be used. JWT supports these reserved claim names:

  • 'exp' (Expiration Time) Claim
  • 'nbf' (Not Before Time) Claim
  • 'iss' (Issuer) Claim
  • 'aud' (Audience) Claim
  • 'jti' (JWT ID) Claim
  • 'iat' (Issued At) Claim
  • 'sub' (Subject) Claim

Expiration Time Claim

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 the exp claim requires that the current date/time MUST be before the expiration date/time listed in the exp claim. Implementers MAY provide for some small leeway, 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.

ruby
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
end

The Expiration Claim verification can be disabled.

ruby
# Decode token without raising JWT::ExpiredSignature error
JWT.decode(token, hmac_secret, true, { verify_expiration: false, algorithm: 'HS256' })

Leeway and the exp claim.

ruby
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
end

Not Before Time Claim

From [Oauth JSON Web Token 4.1.5. "nbf" (Not Before

Issues· 10 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyjwkjwtjwt-tokenoauth-json-web

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category安全
PricingOpen source

> Related tools

O
OWASP ZAP
开源 Web 应用安全扫描器
O
owasp-wstg-tracker
Simple web app to track OWASP WSTG security testing progress
H
homebridge-mi-gateway-security
XiaoMi Gateway Security plugin for HomeBridge.