Skip to content
nov edited this page Sep 11, 2015 · 23 revisions

JSON::JWT

Install

gem install json-jwt

Require

require 'json/jwt'

Supported JOSE Specs

JWT, JWS, JWE, JWK, JWKs are supported.

For details, please read these pages.

Common Use-Cases

OpenID Connect ID Token

Encode

claims = {
  iss: 'https://idp.example.com',
  sub: '1061b047368a15d92ccd882b964a3aa4',
  aud: 'c136b3a6d4f1060316a84af73347ce18',
  nonce: 'b8c5c105b2bfd04516a13f593a91e140',
  iat: 1441949362,
  exp: 1441949736
}
jwt = JSON::JWT.new claims
jws = jwt.sign rsa_private_key
id_token = jws.to_s

Decode

jwt = JSON::JWT.decode id_token, rsa_public_key
unless (
  jwt[:iss] == expected_iss &&
  jwt[:aud] == expected_aud &&
  jwt[:sub].present? &&
  jwt[:nonce] == expected_nonce &&
  jwt[:iat].between?(5.minutes.ago, Time.now) &&
  jwt[:exp] > Time.now
)
  raise 'ID Token Verification Failed!'
end

NOTE: implement verify by your own.

Sing then Encrypt

Encode

jwt = JSON::JWT.new payload
jws = jwt.sign sender_private_key
jwe = jws.encrypt recipient_public_key
jwe.to_s

Decode

jwe = JSON::JWT.decode jwe_string, recipient_private_key
payload = JSON::JWT.decode jwe.plain_text, sender_public_key
Clone this wiki locally