如何实现基于角色的 REST API

编程入门 行业动态 更新时间:2024-10-26 22:16:41
本文介绍了如何实现基于角色的 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

本文发布于:2023-10-11 13:44:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1481862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何实现   角色   API   REST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!