LexikJWTAuthenticationBundle - 如何授予对不同路径的不同访问权限?

LexikJWTAuthenticationBundle - How to grant different access to different path's?

我正在使用 LexikJWTAuthenticationBundle 在使用 REST Web 服务的 Web 应用程序中进行身份验证。

我想将我的申请分成两部分:

等等。

想法是,通过 url:

/api       #reach the public content of the website
/api/admin #reach private admin content, if not logged in -> loginpage

我在 security.yaml 中试过这个:

    access_control:
    - { path: ^/api, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/admin,       roles: IS_AUTHENTICATED_FULLY }

但是当我尝试像这样加载内容时:

curl -X GET <baseurl-backend>/api/content/list #generic example

我得到:

{code: 401, message: "JWT Token not found"}

这里是 security.yaml 的所有配置:

security:
    encoders:
        App\Entity\User:
            algorithm: argon2i

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        login:
            pattern:  ^/api/login
            stateless: true 
            anonymous: true 
            json_login:
                check_path: /api/login_check #path for checking
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
        api:
            pattern:   ^/api
            stateless: true
            guard:
                authenticators:
                - lexik_jwt_authentication.jwt_token_authenticator
        main: 
            anonymous: true

    access_control:
    - { path: ^/api, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/admin,       roles: IS_AUTHENTICATED_FULLY }

感谢您的帮助!

您应该将 anonymous: true 添加到您的 api 防火墙。

api:
    pattern:   ^/api
    stateless: true
    anonymous: true
    guard:
        authenticators:
        - lexik_jwt_authentication.jwt_token_authenticator

如果您想阻止对 api/admin 的访问,您应该在 api 防火墙之上添加另一个防火墙:

api_admin:
    pattern:   ^/api/admin
    stateless: true
    guard:
        authenticators:
        - lexik_jwt_authentication.jwt_token_authenticator
api:
    pattern:   ^/api
    stateless: true
    anonymous: true
    guard:
        authenticators:
        - lexik_jwt_authentication.jwt_token_authenticator