Skip to content
Dan W edited this page Dec 20, 2017 · 6 revisions

JSON Web Token (JWT)

JSON::JWT class is for RFC7519, and it's the core of this gem.

Basically, you'll generate an JSON::JWT instance, then sign and/or encrypt it using JWS and JWE.

Generation

JSON::JWT is a subclass of ActiveSupport::HashWithIndifferentAccess, so you can initialize it in ActiveSupport::HashWithIndifferentAccess way, and access any claims via JSON::JWT#[] like a Hash instance.

jwt = JSON::JWT.new(
  iss: 'nov',
  exp: 1.week.from_now,
  nbf: Time.now
)
jwt[:iss] # => 'nov'

To access JWT header, simply call JSON::JWT#header.

jwt.header # => {typ: :JWT, alg: :none}
jwt.header[:kid] = 'default-key'

Several common header attributes has its shortcut methods (both read & write).

jwt.kid = 'default-key'
jwt.kid # => 'default-key'

jwt.alg = :RS256
jwt.alg # => :RS256

jwt.header # => {typ: :JWT, alg: :RS256, kid: 'default-key'}

Serialization

Simply call JSON::JWT#to_s.

Compact Serialization

jwt.to_s
# => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJpc3MiOiJub3YiLCJleHAiOjE0NDExNzk0NDEsIm5iZiI6MTQ0MDU3NDY0MX0.'

JSON Serialization

This gem also supports JWS/JWE Flattened and General JSON Serialization, multiple signature isn't supported though.

jwt.as_json(syntax: :general)
jwt.as_json(syntax: :flattened)

Decoding

JSON::JWT#decode(token, key) decodes both compact-serialized and json-serialized JWT/JWS/JWE tokens.

If you didn't specify magic symbol (:skip_verification and :skip_decryption), and the token is signed/encrypted, then JSON::JWT#decode also verify/decrypt it using given key.

Each token includes algorithm information in its header, so you don't need to specify which algorithms you want to use to verify/decrypt it.

JSON::JWT.decode 'eyJ..', 'secret'

If the token is not signed nor encrypted, omit key.

JSON::JWT.decode 'eyJ..'
Clone this wiki locally