Class: RackJwtVerifier::JwtHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_jwt_verifier/jwt_helper.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(private_key_pem) ⇒ JwtHelper

Initializes the helper with the RSA Private Key used for signing.

Parameters:

  • private_key_pem (String)

    The PEM string of the RSA Private Key.



16
17
18
19
20
21
# File 'lib/rack_jwt_verifier/jwt_helper.rb', line 16

def initialize(private_key_pem)
  # !! IMPORTANT !!
  # This key signs the tokens.
  @private_key = OpenSSL::PKey::RSA.new(private_key_pem)
  @public_key = @private_key.public_key
end

Instance Attribute Details

#private_keyObject (readonly)

The private_key must be an OpenSSL::PKey::RSA object (or similar).



11
12
13
# File 'lib/rack_jwt_verifier/jwt_helper.rb', line 11

def private_key
  @private_key
end

#public_keyObject (readonly)

The private_key must be an OpenSSL::PKey::RSA object (or similar).



11
12
13
# File 'lib/rack_jwt_verifier/jwt_helper.rb', line 11

def public_key
  @public_key
end

Instance Method Details

#decode(token) ⇒ Hash

Decodes and verifies a JWT using the public key.

NOTE: This method is used primarily for self-testing in the application but the primary verification logic for the middleware is in the Verifier class.

Parameters:

  • token (String)

    The JWT string to decode.

Returns:

  • (Hash)

    The decoded payload if verification is successful.

Raises:

  • (JWT::VerificationError, JWT::DecodeError)

    If the token is invalid or expired.



47
48
49
50
51
52
53
# File 'lib/rack_jwt_verifier/jwt_helper.rb', line 47

def decode(token)
  # Decodes using the public key, performs signature verification (true),
  # and restricts the algorithm to 'RS256'.
  decoded = JWT.decode(token, @public_key, true, { algorithm: 'RS256' })
  # Returns only the payload (the first element of the array).
  decoded.first
end

#encode(payload, expires_in = 3600) ⇒ String

Encodes a payload into a JWT.

Parameters:

  • payload (Hash)

    The data to be encoded in the JWT (e.g., user ID, roles).

  • expires_in (Integer) (defaults to: 3600)

    Time in seconds until the token expires (default: 1 hour).

Returns:

  • (String)

    The signed JWT string.



28
29
30
31
32
33
34
35
36
37
# File 'lib/rack_jwt_verifier/jwt_helper.rb', line 28

def encode(payload, expires_in = 3600)
  # Set standard expiration time (exp) and issued-at time (iat) claims
  time = Time.now.to_i
  payload_with_claims = payload.merge({
    iat: time,
    exp: time + expires_in
  })

  JWT.encode(payload_with_claims, @private_key, 'RS256')
end