首页 > 解决方案 > API 平台 Symfony 5 JWT 访问控制

问题描述

我使用 jwt 令牌启动了一个带有 api 平台的 REST API。主要目的是注册和登录用户。我试图授予未经过身份验证的用户对 post 路由的访问权限, api/users 但以下输出有问题:

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

但是,在没有任何授权承载的情况下获取路由工作。

这是我的 security.yaml

# config/packages/security.yaml
security:
    encoders:
        App\Entity\User:
            algorithm: auto

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        login:
            pattern: ^/api/login
            stateless: true
            anonymous: true
            json_login:
                check_path: /api/login
                username_path: username
                password_path: password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
        api:
            pattern: ^/api/
            stateless: true
            anonymous: true
            provider: app_user_provider
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
        main:
            anonymous: lazy
            provider: app_user_provider

    access_control:
        - { path: ^/api/docs, roles: IS_AUTHENTICATED_ANONYMOUSLY } # Allows accessing the Swagger UI
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api/users, roles: IS_AUTHENTICATED_ANONYMOUSLY }

标签: apirestsymfonyjwtapi-platform.com

解决方案


我解决了我的问题。我只是改变我的模型注释:

collectionOperations={
 *         "get",
 *         "post"={"security"="is_granted('ROLE_USER')"}
 *     }


collectionOperations={
 *         "get",
 *         "post"={"method"="POST", "access_control"="is_granted('IS_AUTHENTICATED_FULLY') === false"}
 *     }

推荐阅读