Module: JsonWebToken::Jwt

Defined in:
lib/json_web_token/jwt.rb

Overview

Encode claims for transmission as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure, enabling the claims to be integrity protected with a Message Authentication Code (MAC), to be later verified

Constant Summary collapse

ALG_DEFAULT =
'HS256'
HEADER_DEFAULT =
{
  typ: 'JWT',
  alg: ALG_DEFAULT
}

Class Method Summary collapse

Class Method Details

.sign(claims, options) ⇒ String

Returns a JSON Web Token, representing digitally signed claims.

Examples:

claims = {iss: 'joe', exp: 1300819380, :'http://example.com/is_root' => true}
options = {alg: 'HS256', key: 'gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C'}
Jwt.sign(claims, options)
# => 'eyJhbGciOiJIUzI1NiJ9.cGF5bG9hZA.uVTaOdyzp_f4mT_hfzU8LnCzdmlVC4t2itHDEYUZym4'

Parameters:

  • claims (Hash)

    a collection of name/value pairs asserting information about a subject

  • options (Hash)

    specify the desired signing algorithm and signing key (e.g String for Hmac | OpenSSL::PKey::RSA | OpenSSL::PKey::EC)

Returns:

  • (String)

    a JSON Web Token, representing digitally signed claims

See Also:



28
29
30
31
32
33
# File 'lib/json_web_token/jwt.rb', line 28

def sign(claims, options)
  message = validated_message(claims)
  header = config_header(options)
  return Jws.unsecured_message(header, message) if header[:alg] == 'none'
  Jws.sign(header, message, options[:key])
end

.verify(jwt, options) ⇒ Hash

Returns {ok: <the jwt claims set hash>} if the jwt verifies, or {error: ‘Invalid’} otherwise.

Examples:

jwt = 'eyJhbGciOiJIUzI1NiJ9.cGF5bG9hZA.uVTaOdyzp_f4mT_hfzU8LnCzdmlVC4t2itHDEYUZym4'
options = {alg: 'HS256', key: 'gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C'}
Jwt.verify(jwt, options)
# => {ok: {iss: 'joe', exp: 1300819380, :'http://example.com/is_root' => true}}

Parameters:

  • jwt (String)

    a JSON Web Token

  • options (Hash)

    specify the desired verifying algorithm and verifying key

Returns:

  • (Hash)

    {ok: <the jwt claims set hash>} if the jwt verifies, or {error: ‘Invalid’} otherwise

See Also:

  • http://tools.ietf.org/html/rfc7519#section-7.2


45
46
47
48
# File 'lib/json_web_token/jwt.rb', line 45

def verify(jwt, options)
  alg = options[:alg] || ALG_DEFAULT
  payload(Jws.verify(jwt, alg, options[:key]))
end