-
-
Notifications
You must be signed in to change notification settings - Fork 81
Home
nov edited this page Aug 26, 2015
·
23 revisions
Install
gem install json-jwt
Require
require 'json/jwt'
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'}
Simply call JSON::JWT#to_s
jwt.to_s
# => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJpc3MiOiJub3YiLCJleHAiOjE0NDExNzk0NDEsIm5iZiI6MTQ0MDU3NDY0MX0.'
In many cases, you will sign and/or encrypt JWTs. (alg=none
won't be used in general) For signing, call JSON::JWT#sign(key, algorithm)
.
These values are supported as algorithm
.
-
HS256
(default) HS384
HS512
RS256
RS384
RS512
ES256
ES384
ES512
For historical reasons, HS256
is the default, but I recommend you to use RS256
if possible. Using shared key isn't a good choice for assertion signing in general.
shared_key = 'shared-key'
jwt.sign(shared_key) # HS256 is the default
jwt.sign(shared_key, :HS384)
jwt.sign(shared_key, :HS512)
private_key = OpenSSL::PKey::RSA.new(2048)
jwt.sign(private_key, :RS256)
jwt.sign(private_key, :RS384)
jwt.sign(private_key, :RS512)
private_key = OpenSSL::PKey::EC.new('prime256v1').generate_key
jwt.sign(private_key, :ES256)
private_key = OpenSSL::PKey::EC.new('secp384r1').generate_key
jwt.sign(private_key, :ES384)
private_key = OpenSSL::PKey::EC.new('secp521r1').generate_key
jwt.sign(private_key, :ES512)
TODO