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) (defaults to: {})

    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:



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

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 a JWT claims set if the jwt verifies, or {error: ‘Invalid’} otherwise.

Examples:

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

Parameters:

  • jwt (String)

    a JSON Web Token

  • options (Hash) (defaults to: {})

    specify the desired verifying algorithm and verifying key

Returns:

  • (Hash)

    a JWT claims set if the jwt verifies, or {error: ‘Invalid’} otherwise

See Also:

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


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

def verify(jwt, options = {})
  alg = options[:alg] || ALG_DEFAULT
  jws = Jws.verify(jwt, alg, options[:key])
  jws ? Util.symbolize_keys(decoded_message_json_to_hash jws) : {error: 'invalid'}
end