LexikJWTAuthenticationBundle returns 401 for an invalid token on an anonymous route

I am using this LexikJWTAuthenticationBundle with FosUserBundle.

I have this in security.yml:

firewalls:
    app:
        pattern: ^/api
        stateless: true
        anonymous: true
        lexik_jwt: ~

with the following access_control:

- { path: ^/api/user/action1, roles: IS_AUTHENTICATED_FULLY }
- { path: ^/api/user/action2, roles: IS_AUTHENTICATED_ANONYMOUSLY }

The behavior that I expected for / api / user / action 2 has access regardless of what is inside the request header. However, I get 401 when the authorization identifier is installed but is not valid (this is normal with a valid token or no authorization media at all).

My use case is that I need to check my controller if the user is logged in, but if not, I still want this anonymous user to be able to access the route.

+4
2

/, :

action2:
    pattern: ^/api/user/action2
    anonymous: true
    lexik_jwt: ~

access_control :

- { path: ^/api/user/action2, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/user/action1, roles: IS_AUTHENTICATED_FULLY }

, - , , JWT.

:

action2:
    pattern: ^/api/user/action2
    anonymous: true
    lexik_jwt: ~

access_control :

- { path: ^/api/user/action2, roles: [IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_FULLY]  }
- { path: ^/api/user/action1, roles: IS_AUTHENTICATED_FULLY }

, .

JWT/FOSUB, , .

:

$currentToken = $this->get('security.token_storage')->getToken();

if (is_object($currentToken->getUser())) {
    // Do your logic with the current user
    return new JsonResponse(['user' => $currentToken->getUser()->getUsername()]);
} else {
    return new JsonResponse(['user' => 'Anonymous']);
}

, .

+1

:

    api_public:
        pattern: ^/api/v1/public
        anonymous: true
        lexik_jwt:
            authorization_header:
                enabled: false
                prefix:  Bearer
            query_parameter:
                enabled: false
                name:    bearer
    api:
        pattern:   ^/api
        stateless: true
        anonymous: true
        lexik_jwt:
            authorization_header:
                enabled: true
                prefix:  Bearer
            query_parameter:
                enabled: true
                name:    bearer
0

Source: https://habr.com/ru/post/1628531/


All Articles