如何实现基于角色的 REST API [英] How to implement Role-based REST API
问题描述
我的项目中有两个不同的角色:ROLE_USER
和 ROLE_ADMIN
.
我想通过 REST API's url '/users'
获取所有用户的列表,但某些字段(例如 email
)只能看到那些使用 ROLE_ADMIN
进行身份验证的人.
所以,我通常有两个问题:
I have two different roles in my project: ROLE_USER
and ROLE_ADMIN
.
I want to get list of all users through REST API's url '/users'
, but some fields (for example email
) can see only those person, who authenticated with ROLE_ADMIN
.
So, I have generally 2 questions:
1) 我应该在哪个抽象级别(在MVC
模式中)根据ROLE
决定可以返回哪些信息2) 在 Symfony 中实现这种基于角色的 REST API 的最佳方法是什么?
谢谢
推荐答案
如果您使用 JMSSerializer
,您可以使用组来决定哪些内容可以被看到.然后在您的控制器中或其他任何地方,您可以根据角色设置组.
If you are using JMSSerializer
you can use groups to decide what can be seen or not. Then in your controller, or where ever, you could set the group based on the role.
例如使用映射(在 YAML 中)..
For example with the mapping (in YAML)..
Fully\Qualified\Class\Name:
exclusion_policy: ALL
properties:
id:
groups: [user]
userAndAdmin:
groups: [user]
adminOnly:
groups: [admin]
然后在您的控制器中,您可以将组设置为...
And then in your controller you would set the group like...
public function getUsersAction(Request $request)
{
$users = $this->getRepository()->findAll();
$serializer = $this->get('jms_serializer.serializer');
$json = $serializer->serialize(
$users,
'json',
SerializationContext::create()->setGroups($this->generateGroups())
);
return new Response($json);
// If you are using FOSRestBundle, which I would recommend, then you would just need to do...
$view = $this
->view($this->getRepository()->findAll();)
->setExclusionGroups($this->generateGroups())
;
return $this->handleView($view);
}
private function generateGroups()
{
$securityContext = $this->get('security.context');
$groups = array();
if ($securityContext->isGranted('ROLE_USER')) {
$groups[] = 'user';
}
if ($securityContext->isGranted('ROLE_ADMIN')) {
$groups[] = 'admin';
}
return $groups;
}
虽然整个generateGroups"和设置组最好放在客户视图处理程序或响应生成器中.
Although the whole "generateGroups" and setting the groups would be better placed in a customer view handler or response generator.
假设您的层次结构将 ROLE_ADMIN
作为 ROLE_USER
的父级,您将得到以下结果.
Assuming your hierarchy has ROLE_ADMIN
as a parent of ROLE_USER
you would get the following results.
ROLE_USER
{
"users": [
{
"id": 1,
"userAndAdmin": "val"
}
]
}
ROLE_ADMIN
{
"users": [
{
"id": 1,
"userAndAdmin": "val",
"adminOnly": "val"
}
]
}
这篇关于如何实现基于角色的 REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!