Class: RackJwtVerifier::Middleware
- Inherits:
-
Object
- Object
- RackJwtVerifier::Middleware
- Defined in:
- lib/rack_jwt_verifier/middleware.rb
Overview
The primary middleware class responsible for intercepting requests, extracting the JWT, verifying it, and injecting the user’s details into the Rack environment.
Constant Summary collapse
- RACK_ENV_PAYLOAD_KEY =
The default key in the Rack environment used to store the verified JWT payload. This can be accessed by downstream applications (e.g., Rails controllers) to retrieve the authenticated user’s details.
"rack_jwt_verifier.payload".freeze
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ Middleware
constructor
A new instance of Middleware.
Constructor Details
#initialize(app, options = {}) ⇒ Middleware
Returns a new instance of Middleware.
15 16 17 18 19 20 21 22 |
# File 'lib/rack_jwt_verifier/middleware.rb', line 15 def initialize(app, = {}) @app = app @options = # The Verifier instance is initialized with options (like public_key_url) # and is responsible for all crypto and key management. @verifier = Verifier.new() end |
Instance Method Details
#call(env) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/rack_jwt_verifier/middleware.rb', line 24 def call(env) token = extract_token(env) # If no token is found, we immediately pass the request down the stack # and the application is responsible for handling the unauthenticated state. return @app.call(env) unless token begin # Use the Verifier to handle the complex crypto and validation logic payload = @verifier.verify(token) # On successful verification, store the payload in the Rack environment env[RACK_ENV_PAYLOAD_KEY] = payload @app.call(env) rescue JWT::DecodeError => e # If verification fails (invalid signature, expired, invalid claim), # log the error and return an unauthenticated response. warn "JWT Verification Failed: #{e.}" # Return a 401 Unauthorized response end end |