symfony里实现resfull api并实现权限控制
----------------------------------------------------------
1、restfull api部分
注:笔记,自己摸索出来的,路子野,仅供参考。
----------------------- 欢迎指教交流。。。
<?php
// BaseController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class BaseController extends Controller
{
protected static $method_type = array('get', 'post', 'put', 'patch', 'delete');
/**
* description: 负责restfull api调派
* @param {request obj,class||obj,[array],string}
* @return: array
*/
public static function restfullDispatch(Request $request,$obj,$params=null,$resouce=null){
$resouce = $resouce ? $resouce:explode('Action',explode('Controller::',$request->get('_controller'))[1])[0];
$method = strtolower($request->server->get('REQUEST_METHOD'));
if (in_array($method, self::$method_type)) {
//调用请求方式对应的方法
$method_name = $method . ucfirst($resouce);
if(!method_exists($obj,$method_name)){
throw new Exception('The method: '.$method_name.' not exists!');
}
return $obj->$method_name($params);
}
return false;
}
}
然后所有controller继承BaseController,Action调$this::restfullDispatch() 就行了,最后路由可以设置成类似:
get /admin/user
post /admin/user
put /admin/user
patch /admin/user
……
2、权限控制部分
其实也很简单,由于开始时没有认真看框架的 事件监听 部分的文档,摸索了很久。。。这里做个记录。
简单总结为以下几个步骤:
1、securty.yml里配置好角色继承关系
security:
#···
#分层角色
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
^ROLE_CUSTOM_: ROLE_USER #自定义角色需继承ROLE_USER才能登录,没错可以用正则,棒棒的
2、数据库里建立RBAC关系表(这部分基本和别的框架一样)
数据库大概是这个样子:
角色表
权限表表
用户表里面有一个role字段,值为角色表里的一条记录的name,就不截图了
3、监听kener.controller事件,根据role的验证权限,根据验证结果setController
<?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpFoundation\Response;
// use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
// use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use AppBundle\System\Status;
use AppBundle\Entity\Users;
use AppBundle\Entity\Roles;
/**
* 侦听系统的kernel.controller事件,通过actionName实现权限控制
*/
class RunActionListenter
{
protected $controllerConfig = array('Admin'); //需要进行权限控制的controller
protected $em;
protected $tokenStorage;
protected $result = array(
'code' => Status::ALL['PERMISSION_DENIED'][0],
'msg' => Status::ALL['PERMISSION_DENIED'][1],
'data' => null,
);
public function __construct(TokenStorageInterface $tokenStorage,ContainerInterface $container){
$this->tokenStorage = $tokenStorage;
$this->em = $container->get('doctrine')->getManager();
}
public function onKernelController(FilterControllerEvent $event){
if(! $event->isMasterRequest()){
return;
}
$request = $event->getRequest();
$isAjax = $request->isXmlHttpRequest();
$method = strtolower($request->server->get('REQUEST_METHOD'));
$controller = explode('Controller::',$request->get('_controller'));
$controllerName = substr($controller[0],21);
if(in_array($controllerName,$this->controllerConfig)){
$user = $this->tokenStorage->getToken()->getUser();
//超级管理员只做登录验证,此角色可以为所欲为,并且不能通过系统的权限管理分配到此角色
if(! $user->hasRole('ROLE_SUPER_ADMIN')){
$actionName = $method.ucfirst(explode('Action',$controller[1])[0]);
$userRole = $user->getRoles()[0];
$privileges = $this->em->getRepository(Roles::class)
->findOneBy(array('name'=>$userRole))->getPrivileges();
// $privilegeId = $this->em->getRepository('AppBundle\Entity\privileges')
// ->findOneBy(array('actionName'=>$actionName))->getId();
if(!in_array($actionName,$privileges)){
$this->result['msg'] = $this->result['msg'].',你当前的职位还需要权限:'.$actionName.'才能继续访问,请【联系管理员授权】!';
$controller = $event->getController()[0];
$event->setController(function() use ($isAjax){
if($isAjax){
return new Response(
json_encode($this->result,true),
200,
array('Content-Type' => 'application/json')
);
}else{
return new Response('<h4>'.$this->result['msg'].'</h4>');
}
});
}
}
}
}
}
然后别忘了按照文档说的在service.yml里把它写进去
-----------over。。。
------------------------------------------------------------------------
symfony里实现resfull api并实现权限控制的更多相关文章
- 在ASP.NET MVC里对Web Page网页进行权限控制
我们在ASP.NET MVC开发时,有时候还是得设计ASP.NET的Web Page网页(.aspx和.aspx.cs),来实现一些ASP.NET MVC无法实现的功能,如此篇<Visual S ...
- 基于RESTful API 设计用户权限控制
RESTful简述 本文是基于RESTful描述的,需要你对这个有初步的了解. RESTful是什么? Representational State Transfer,简称REST,是Roy Fiel ...
- Android开发-API指南-系统权限
System Permissions 英文原文:http://developer.android.com/guide/topics/security/permissions.html 采集日期:201 ...
- API权限控制与安全管理
摘自网上 一.API权限控制范围 1.首先验证web端请求参数: (1)web请求参数:渠道.ServiceName.版本.Airline.时间戳(yyyyMMddhhmmssSSS).reqXML ...
- Spring Boot 之 RESRful API 权限控制
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “简单,踏实~ 读书写字放屁” 一.为何用RESTful API 1.1 RESTful是什么? ...
- 认证鉴权与API权限控制在微服务架构中的设计与实现(四)
引言: 本文系<认证鉴权与API权限控制在微服务架构中的设计与实现>系列的完结篇,前面三篇已经将认证鉴权与API权限控制的流程和主要细节讲解完.本文比较长,对这个系列进行收尾,主要内容包括 ...
- Expo大作战(三十)--expo sdk api之Permissions(权限管理模块),Pedometer(计步器api)
简要:本系列文章讲会对expo进行全面的介绍,本人从2017年6月份接触expo以来,对expo的研究断断续续,一路走来将近10个月,废话不多说,接下来你看到内容,讲全部来与官网 我猜去全部机翻+个人 ...
- 基于RESTful API 怎么设计用户权限控制?
前言 有人说,每个人都是平等的:也有人说,人生来就是不平等的:在人类社会中,并没有绝对的公平,一件事,并不是所有人都能去做:一样物,并不是所有人都能够拥有.每个人都有自己的角色,每种角色都有对某种资源 ...
- 【微服务】之七:轻松搞定SpringCloud微服务-API权限控制
权限控制,是一个系统当中必须的重要功能.张三只能访问输入张三的特定功能,李四不能访问属于赵六的特定菜单.这就要求对整个体系做一个完善的权限控制体系.该体系应该具备针区分用户.权限.角色等各种必须的功能 ...
- gin-jwt对API进行权限控制
前言 之前文章简单介绍了如何运行gin+vue的前后端分离开源项目,该项目是学习了Gin实践教程后结合vue-element-admin写的,该教程讲得很详细,适合入门Gin.本篇文章将介绍gin+v ...
随机推荐
- LeetCode刷题小白必看!如何科学地刷题,从0到1建立你的算法体系?
大家好,我是忍者算法的作者,今天想和大家聊聊如何科学地刷题.如果你是一个刚开始刷题的小白,面对LeetCode上密密麻麻的题目感到无从下手,或者刷了一段时间却发现自己进步缓慢,那么这篇文章就是为你准备 ...
- 手把手教你部署 DeepSeek 本地模型
本文目标:部署 DeepSeek 本地模型,并通过 Ollama 提供 API 支持,Chatbox 提供 UI 界面. 原则:不搞那些高深的玩法,让小白也能理解并真正的上手实践. 1.下载Ollam ...
- Keepalived基本原理
本文分享自天翼云开发者社区<Keepalived基本原理>,作者:Ujnrfc Keepalived简介 Keepalived是Linux下一个轻量级别的高可用解决方案.高可用:广义来讲, ...
- ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this
mysql操作错误: mysql> use mysql;ERROR 1820 (HY000): You must reset your password using ALTER USER sta ...
- clickhouse--数据类型
数据类型 整型 固定长度的整型,包括有符号整型或无符号整型. 整型范围(-2n-1~2n-1-1): Int8 - [-128 : 127] Int16 - [-32768 : 32767] Int3 ...
- burpsuite激活
激活burpsuite--教程 点击Start 文件,把三个框都选上 点击RUN,会自动启动,复制一下那个证书 粘贴刚刚复制的密钥,点击下一个即可 这里点击手动激活,复制请求,粘贴到刚刚那个激活程序的 ...
- k8s node节点报错 dial tcp 127.0.0.1:8080: connect: connection refused
前言 在搭建好 kubernetes 环境后,master 节点拥有 control-plane 权限,可以正常使用 kubectl. 但其他 node 节点无法使用 kubectl 命令,即使同步过 ...
- mongodb logical sessions can't have multiple authenticated users
前言 使用 mongodb db.auth,切换用户时,报以下错误 logical sessions can't have multiple authenticated users 原因是 mongo ...
- Joker 前端框架组件的生命周期:深度解析与实践应用
在 Joker 前端框架的开发体系中,组件的生命周期犹如一颗精准的导航星,指引着开发者构建高效.稳定且富有交互性的应用程序.它完整地涵盖了从组件实例诞生的那一刻起,直至其完成使命被销毁的全过程,每一个 ...
- PLSQL中查询数据的时候查询结果显示中文乱码
要需要很努力才能看起来毫不费力.....1.在PLSQL中查询数据的时候查询结果显示中文乱码这里写图片描述2.需要在环境变量中新建两个环境变量:第一个:设置 NLS_LANG=SIMPLIFIED C ...