| sidebar_position | 12 |
|---|---|
| sidebar_label | JWT Authentication |
Note: For general middleware usage patterns, see Middleware.
The JWT Middleware is a middleware that will validate the JWT token in the Authorization header.
If the token is valid, it will add the jwt attribute to the request with the decoded token.
<?php
use ByJG\RestServer\Middleware\JwtMiddleware;
$jwtKey = new JwtKeySecret("password", false);
$jwtWrapper = new JwtWrapper("localhost", $jwtKey);$jwtMiddleware = new JwtMiddleware($jwtWrapper);Once the page is processed, the middleware will add the jwt attribute to the request with the decoded parameters.
Valid values are:
- JwtMiddleware::JWT_PARAM_PARSE_STATUS_OK
- JwtMiddleware::JWT_PARAM_PARSE_STATUS_ERROR
$request->param(JwtMiddleware::JWT_PARAM_PARSE_STATUS)$request->param(JwtMiddleware::JWT_PARAM_PARSE_MESSAGE)// KEY is the key defined in the token
$request->param(JwtMiddleware::JWT_PARAM_PREFIX . "." . $KEY);You can configure the JWT middleware to ignore specific paths, which allows public access to certain routes without requiring JWT authentication:
<?php
// Define paths to ignore (using regular expressions)
$ignorePaths = [
'^/public/.*', // Ignore all paths starting with /public/
'/auth/login', // Ignore the login endpoint
'/docs/.*' // Ignore documentation routes
];
// Create the middleware with ignore paths
$jwtMiddleware = new JwtMiddleware($jwtWrapper, $ignorePaths);- For each request, the middleware checks if the request path matches any pattern in the ignore list
- If a match is found, the middleware skips token validation and allows the request to proceed
- If no match is found, the middleware validates the JWT token as usual
The ignore paths use PHP's regular expression format:
^/api/public/.*- All paths that start with/api/public//auth/login- Exact match for/auth/login.*\.(jpg|png|gif)$- All paths that end with .jpg, .png or .gif
- Public API documentation endpoints
- Authentication endpoints (login, register)
- Public resource endpoints
- Health check endpoints
- Static file serving