Hug*_*ira 5 php oauth symfony fosoauthserverbundle
我有一个基本的api,使用FOSOAuthServerBundle验证用户.用户可以拥有ROLE_USER和ROLE_ADMIN角色.基于FOSOAuthServerBundle文档,默认行为是使用范围的角色,所以我认为,当我有一个普通用户,捆绑将返回scope: user的响应,并且当它是一个管理员用户,将返回scope: admin.但它不是这样的.捆绑包返回supported_scopes条目中配置的任何内容.以下是我的config.yml.
fos_oauth_server:
service:
options:
supported_scopes: user admin
Run Code Online (Sandbox Code Playgroud)
我的access_control部分security.yml是空的,我的firewalls部分如下:
firewalls:
users_create:
pattern: ^/v1/users
methods: [POST]
security: false
api:
pattern: ^/
security: true
fos_oauth: true
stateless: true
access_control:
# You can omit this if /api can be accessed both authenticated and anonymously
Run Code Online (Sandbox Code Playgroud)
这样user admin,即使用户没有ROLE_ADMIN角色,bundle也始终作为作用域返回.
{
"access_token": "ZGQ2ODE5ZjAzNTZkOWY0OWMyNmZmODE4MjcwZTJmYjExNzY0NzQxOTRmMzk4NzA2Mjc2NjIyZmY1ZDgwMzk4NA"
"expires_in": 3600
"token_type": "bearer"
"scope": "user admin"
"refresh_token": "NmM5ZGFmNzBiNTNjYmQzMTQ1MTk0ODJjOTAxMWU0YWIwMzM1MzgyODg4ZTAzNTI5ZTk2MDc3OGU2MTg0MWZiMA"
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么?用户角色是否附加到令牌范围?有没有更好的方法来了解我的用户是否是管理员?
从文档来看,默认行为是将范围与角色映射。在您的情况下,角色将为 ROLE_USER 和 ROLE_ADMIN。
现在为了限制使用,您可以像这样编辑 security.yml 文件:
# app/config/security.yml
security:
access_control:
- { path: ^/api/super/secured, role: ROLE_ADMIN }
- { path: ^/api/general, role: ROLE_USER }
Run Code Online (Sandbox Code Playgroud)
要限制控制器内部的访问,您可以使用以下命令:
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
// the user has the ROLE_ADMIN role, so act accordingly
}
Run Code Online (Sandbox Code Playgroud)
再次从文档中,
现在,客户端在请求访问令牌时将能够传递范围参数。
希望这可以帮助。
更新:
请参阅此处对类似问题的回答以及有关设置 FOSOAuthServerBundle 的文章。密切关注配置部分。