Class: RackJwtVerifier::JwtHelper
- Inherits:
-
Object
- Object
- RackJwtVerifier::JwtHelper
- Defined in:
- lib/rack_jwt_verifier/jwt_helper.rb
Instance Attribute Summary collapse
-
#private_key ⇒ Object
readonly
The private_key must be an OpenSSL::PKey::RSA object (or similar).
-
#public_key ⇒ Object
readonly
The private_key must be an OpenSSL::PKey::RSA object (or similar).
Instance Method Summary collapse
-
#decode(token) ⇒ Hash
Decodes and verifies a JWT using the public key.
-
#encode(payload, expires_in = 3600) ⇒ String
Encodes a payload into a JWT.
-
#initialize(private_key_pem) ⇒ JwtHelper
constructor
Initializes the helper with the RSA Private Key used for signing.
Constructor Details
#initialize(private_key_pem) ⇒ JwtHelper
Initializes the helper with the RSA Private Key used for signing.
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_key ⇒ Object (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_key ⇒ Object (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.
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.
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 |