Module: JsonWebToken::Jws

Defined in:
lib/json_web_token/jws.rb

Overview

Represent content to be secured with digital signatures or Message Authentication Codes (MACs)

Constant Summary collapse

MESSAGE_SIGNATURE_PARTS =
3

Class Method Summary collapse

Class Method Details

.sign(header, payload, key) ⇒ String

Returns a JSON Web Signature, representing a digitally signed payload.

Examples:

header = {alg: 'HS256'}
key = 'gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C'
Jws.sign(header, 'payload', key)
# => 'eyJhbGciOiJIUzI1NiJ9.cGF5bG9hZA.uVTaOdyzp_f4mT_hfzU8LnCzdmlVC4t2itHDEYUZym4'

Parameters:

  • header (Hash)

    the desired set of JWS header parameters

  • payload (String)

    content to be used as the JWS payload

  • key (String | OpenSSL::PKey::RSA | OpenSSL::PKey::EC)

    secret key used to sign a digital signature, or mac

Returns:

  • (String)

    a JSON Web Signature, representing a digitally signed payload

See Also:



26
27
28
29
30
# File 'lib/json_web_token/jws.rb', line 26

def sign(header, payload, key)
  alg = alg_parameter(header)
  signing_input = encode_input(header, payload)
  "#{signing_input}.#{signature(alg, key, signing_input)}"
end

.unsecured_message(header, payload) ⇒ String

Returns a JWS that provides no integrity protection (i.e. lacks a signature).

Examples:

header = {alg: 'none'}
Jws.sign(header, 'payload')
# => 'eyJhbGciOiJub25lIn0.cGF5bG9hZA.'

Parameters:

  • header (Hash)

    the desired set of JWS header parameters

  • payload (String)

    content to be used as the JWS payload

Returns:

  • (String)

    a JWS that provides no integrity protection (i.e. lacks a signature)

See Also:



40
41
42
43
# File 'lib/json_web_token/jws.rb', line 40

def unsecured_message(header, payload)
  fail("Invalid 'alg' header parameter") unless alg_parameter(header) == 'none'
  "#{encode_input(header, payload)}." # note trailing '.'
end

.verify(jws, algorithm, key = nil) ⇒ Hash

Returns {ok: <the jws string>} if the mac verifies, or {error: ‘invalid’} otherwise.

Examples:

jws = 'eyJhbGciOiJIUzI1NiJ9.cGF5bG9hZA.uVTaOdyzp_f4mT_hfzU8LnCzdmlVC4t2itHDEYUZym4'
key = 'gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr9C'
Jws.verify(jws, 'HS256', key)
# => {ok: 'eyJhbGciOiJIUzI1NiJ9.cGF5bG9hZA.uVTaOdyzp_f4mT_hfzU8LnCzdmlVC4t2itHDEYUZym4'}

Parameters:

  • jws (String)

    a JSON Web Signature

  • algorithm (String)

    ‘alg’ header parameter value for JWS

  • key (String | OpenSSL::PKey::RSA | OpenSSL::PKey::EC) (defaults to: nil)

    key used to verify a digital signature, or mac

Returns:

  • (Hash)

    {ok: <the jws string>} if the mac verifies, or {error: ‘invalid’} otherwise

See Also:



57
58
59
60
61
# File 'lib/json_web_token/jws.rb', line 57

def verify(jws, algorithm, key = nil)
  validate_alg_match(jws, algorithm)
  return {ok: jws} if algorithm == 'none'
  signature_verify?(jws, algorithm, key) ? {ok: jws} : {error: 'invalid'}
end