A new version of ruby-jwt is out with some new and shiny features. This version also is preparing to get rid of some functionality bloating the Gem.
Removing functionality
The plan is that this version is going to be the last one supporting the indirect dependency to rbnacl that powers a few cpypto algorithms (Ed25519 and SHA512256). In the future the SHA512256 algorithm is going to be totally removed as it’s not really an official one. The Ed25519 is moved to the jwt-eddsa gem with it’s own explicit dependency requirements.
Also there will be a number of other breaking changes, read more about them here.
Objects for managing tokens
Over the years the static methods JWT.encode
and JWT.decode
has served us well, but it has been pretty clear that for more advanced use cases the two methods and their parameters have gotten a bit bloated. To preserve backwards compatibility as good as possible the methods are going to stick with us but there is now an alternative way to handle JWT tokens.
Meet the new token classes JWT::Token
and JWT::EncodedToken
. Let’s illustrate the usage with some code samples.
JWT::Token
to sign and encode tokens
token = JWT::Token.new(payload: { exp: Time.now.to_i + 60,
jti: '1234',
sub: "my-subject" },
header: { kid: 'hmac' })
token.sign!(algorithm: 'HS256', key: "secret")
token.jwt # => "eyJhbGciOiJIUzI1N..."
JWT::EncodedToken
to decode and verify tokens
The class can be used to encode and verify signatures and claims.
encoded_token = JWT::EncodedToken.new(token.jwt)
encoded_token.verify_signature!(algorithm: 'HS256', key: "secret")
encoded_token.verify_claims!(:exp, :jti)
encoded_token.payload # => { 'exp'=>1234, 'jti'=>'1234", 'sub'=>'my-subject' }
encoded_token.header # {'kid'=>'hmac', 'alg'=>'HS256'}
A bit more advanced example on how to verify a token with a JWK.
jwk = JWT::JWK.new(OpenSSL::PKey::RSA.generate(2048))
token = JWT::Token.new(payload: { exp: Time.now.to_i + 60 },
header: { kid: jwk.kid })
token.sign!(algorithm: 'RS256', key: jwk.keypair)
encoded_token = JWT::EncodedToken.new(token.jwt)
finder = ->(t) { JWT::JWK::KeyFinder.new(jwks: [jwk]).key_for(t.header['kid']) }
encoded_token.verify_signature!(algorithm: 'RS256',
key_finder: finder)
encoded_token.verify_claims!(:exp)
trusted_payload = encoded_token.payload