Middleware

OAuth2 JWKS Middleware

Introduction

The Auth JWKS middleware provides a secure, automated way to validate JSON Web Tokens (JWTs) against a JSON Web Key Set (JWKS). It is designed to integrate seamlessly with OpenID Connect (OIDC) providers such as Keycloak, Auth0, or Okta.

Key features include:

  • Remote Key Validation: Automatically fetches and caches public keys from a jwksUri to verify token signatures.
  • Scope Validation: Enforces access control by checking for required scopes (e.g., email, profile) within the token.
  • CORS Support: Built-in handling for OPTIONS preflight requests.
  • Path Whitelisting: Easily exclude specific routes (like health checks) from authentication requirements.

Installation

Install the middleware via composer by running:

composer require kipchak/middleware-auth-jwks

Configuration

The configuration in auth.jwks.php can be used to configure this middleware. This file defines the identity provider connection and validation rules.

Global Settings

  • enabled (bool): Master switch. Set to true to enforce authentication globally.
  • jwksUri (string): Required. The URL where your Identity Provider publishes its JSON Web Key Set.
    • Example: 'https://auth.islamic.network/auth/realms/islamic-network/protocol/openid-connect/certs'

Request Handling

  • ignore_options (bool): If true, OPTIONS requests (used for CORS preflight checks) are allowed through without a token.
  • ignore_paths (array): A list of URI paths that should be publicly accessible.
    • Default: ['/status']

Scope Validation

  • validate_scopes (bool): If true, the middleware will verify that the token contains the specific scopes listed in the scopes array.
  • scopes (array): The list of required scopes that must be present in the JWT for the request to be authorized.
    • Default: ['email', 'profile']

Usage

Once enabled, the middleware inspects the Authorization header of incoming requests. It expects a Bearer Token format:

Authorization: Bearer <token>

Basic Workflow

  1. Header Check: The middleware looks for the Authorization header. If missing, the request is denied (unless the path is in ignore_paths).
  2. Signature Verification: The token's signature is validated against the public keys fetched from the jwksUri.
  3. Expiration Check: The middleware ensures the token is not expired (exp claim).
  4. Scope Check: If validate_scopes is enabled, it ensures the token claims include the required permissions.

Customizing Validation per Route

While the config file sets global defaults, you can pass custom scopes when assigning the middleware to specific routes. See the implementation in the starter project, for example.

Git Repository

The source code for this driver is available on 1x.ax at https://1x.ax/mamluk/kipchak/middlewares/subashi.

Previous
Subashi WAF