首页 > 解决方案 > 使用 symfony 身份验证器和 lexik jwt 身份验证

问题描述

我正在开发一个 symfony 4 项目:我使用 API 平台创建了一个文档化的 API,API 公开要从外部使用的数据,现在,我想添加一个仪表板进行管理。API 路由受 jwt lexik bundle 保护,我生成了 symfony 身份验证器。

我的 security.yaml 文件:

security:
    encoders:
        App\Entity\AppUser:
            algorithm: auto
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\AppUser
                property: email
        # used to reload user from session & other features (e.g. switch_user)
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            stateless: true
            anonymous: true
            provider: app_user_provider
            json_login:
                check_path: /authentication_token
                username_path: email
                password_path: password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
                    - App\Security\LoginFormAuthenticator
                entry_point: lexik_jwt_authentication.jwt_token_authenticator
            logout:
                path: app_logout
                # where to redirect after logout
                # target: app_any_route
        refresh:
            pattern:  ^/token/refresh
            ...
    access_control:
        ....
        - { path: ^/administrator, roles: IS_AUTHENTICATED_FULLY }

我想同时使用:jwt 令牌和 symfony 身份验证器来管理管理员角色并添加一个管理系统来处理我的项目的数据。现在当我打开网址时:

http://my-project/administrator

我收到了这条消息:

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

标签: symfonylexikjwtauthbundleauthenticator

解决方案


这个问题有点老了,但只是为了记录,我遇到了类似的需求,并按照文档建议使用 isGranted Annotation 解决了这个问题:

在按照文档建议的实体创建roles属性后,您可以验证用户是否有权访问或没有在方法或整个类上声明 trought 注释:User

use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

...

 /**
  * Require ROLE_ADMIN for *every* controller method in this class.
  *
  * @IsGranted("ROLE_ADMIN")
  */

无需access_control在 security.yaml 上声明部分。


推荐阅读