Symfony合并防火墙:支持匿名与JWT认证用户共存可行吗?
Can I merge Symfony's auth and api firewalls to allow all access while recognizing JWT-authenticated users?
Absolutely, this is totally achievable! You can combine your two firewalls into a single configuration that handles both anonymous access and JWT authentication—so all endpoints are open to everyone, but valid JWT tokens will still trigger proper user authentication.
Here's the adjusted security.yaml configuration to make this work:
firewalls: api: pattern: ^/api stateless: true anonymous: true # Allow unauthenticated users to access all endpoints json_login: check_path: /api/auth/login_check success_handler: lexik_jwt_authentication.handler.authentication_success failure_handler: lexik_jwt_authentication.handler.authentication_failure require_previous_session: false guard: authenticators: - lexik_jwt_authentication.jwt_token_authenticator access_control: - { path: ^/api, roles: IS_AUTHENTICATED_ANONYMOUSLY }
Key changes explained:
- Single firewall for all
/apiroutes: We've merged your originaluserandapifirewalls into one that covers the entire/apipath prefix, eliminating redundant configurations. anonymous: true: This ensures unauthenticated users can access every endpoint without being blocked.- Both authenticators retained: The
json_loginhandler still manages the login endpoint to issue JWT tokens, while thejwt_token_authenticatorchecks for valid tokens in incoming requests. - Simplified access control: A single rule grants anonymous access to all
/apiroutes. When a valid JWT is present (typically via anAuthorization: Bearer <token>header), Symfony will automatically authenticate the user and populate theUserobject in your controllers.
How it operates:
- For requests without a JWT token: The firewall treats the user as anonymous, and access is granted immediately.
- For requests with a valid JWT token: The
jwt_token_authenticatorvalidates the token, loads the corresponding user, and sets them as the authenticated user in the request. You can check if a user is authenticated in your controllers using$this->getUser()or security voters whenever needed.
This setup keeps your endpoints open while maintaining the ability to identify authenticated users when a token is provided—exactly what you're looking for.
内容的提问来源于stack exchange,提问作者Anton Medvedev
相关产品推荐
相关产品推荐

