【问题标题】:LexikJWTAuthenticationBundle - How to grant different access to different path's?LexikJWTAuthenticationBundle - 如何授予对不同路径的不同访问权限?
【发布时间】:2019-09-26 06:22:14
【问题描述】:

我正在使用 LexikJWTAuthenticationBundle 在我的 Web 应用程序中使用 REST 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 }

感谢您的帮助!

【问题讨论】:

    标签: authentication jwt fosrestbundle lexikjwtauthbundle symfony-4.2


    【解决方案1】:

    您应该将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
    

    【讨论】:

    • 不需要再添加防火墙,access_control设置就够了。
    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多