Symfony Flex集成LexikJWTAuthenticationBundle 2.4遇/login_check路由配置问题
Great news—you don’t need to create a custom controller for /login_check! This endpoint is handled internally by LexikJWTAuthenticationBundle, but your security and routing configurations are missing key pieces that tell Symfony to route requests to the bundle’s built-in handler. Let’s walk through the fixes step by step:
1. Correct Your security.yaml Configuration
Your current login firewall has an incomplete pattern and missing critical settings. Update it to match this full, working setup:
security: encoders: App\Entity\User: algorithm: bcrypt providers: entity_provider: entity: class: App\Entity\User property: username users: id: App\Metier\Provider\UserProvider firewalls: login: pattern: ^/login_check # Targets exactly the login_check endpoint stateless: true # Required for JWT (no session storage) anonymous: true # Allow unauthenticated access to this route json_login: check_path: /login_check success_handler: lexik_jwt_authentication.handler.authentication_success failure_handler: lexik_jwt_authentication.handler.authentication_failure main: pattern: ^/ # Protect all other routes stateless: true jwt: ~ # Use JWT authentication for these routes access_control: - { path: ^/login_check, roles: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/, roles: IS_AUTHENTICATED_FULLY }
Key Details:
- The
loginfirewall explicitly targets/login_checkwithpattern: ^/login_check. stateless: trueensures Symfony doesn’t create sessions (essential for JWT’s stateless nature).anonymous: truelets unauthenticated users reach the login endpoint to get their token.- The
json_loginsection connects the endpoint to the bundle’s success/failure handlers, which generate and return the JWT token.
2. Define the /login_check Route
Symfony needs to recognize the /login_check path as a valid route. Add this to your config/routes.yaml:
login_check: path: /login_check methods: [POST] # Only accept POST requests (required for login)
3. Verify the Request Format
When testing, make sure you send a POST request to /login_check with a JSON body containing your user credentials:
{ "username": "your-username", "password": "your-password" }
4. Clear Your Cache
After making these config changes, clear Symfony’s cache to ensure the updates take effect:
php bin/console cache:clear
Troubleshooting Quick Checks
- Confirm LexikJWTAuthenticationBundle is enabled in
config/bundles.php(Symfony Flex should have added this automatically, but double-check):Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle::class => ['all' => true], - Ensure your custom
UserProvider(if using it) correctly returns a validApp\Entity\Userobject for existing users.
内容的提问来源于stack exchange,提问作者Nirina-aj

