symfony - 使用 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"}
解决方案
这个问题有点老了,但只是为了记录,我遇到了类似的需求,并按照文档建议使用 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 上声明部分。
推荐阅读
- authentication - 如何配置 tomcat 8 以支持 SCEP。MDM 所需
- android - 为什么 Room.databaseBuilder 函数需要上下文作为 Room 数据库中的参数?
- javascript - VS Code - 函数括号前的空格,for/while/if 语句
- asp.net-mvc - 使用 EntityFramwork 数据源的 SSRS 报告不显示在 ReportViewer 中
- reactjs - 如何使用 react 和 redux 从不同/其他页面滚动到视图?
- node.js - 如何在nodejs中的选项中循环url
- javascript - 如何始终使用 selenium java 在日期选择器中从当前日期开始 21 天选择日期
- go - go get -u github.com/onsi/ginkgo/ginkgo 突然开始抛出错误
- ios - 弹出显示没有迅速覆盖整个屏幕
- google-sheets - Google Sheet 中的数组约束公式问题