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 ...
随机推荐
- vue平铺日历组件
vue日历自定义平铺组件 <sy-icon @click="preMon" class="copy-icon" iconClass="iconj ...
- Nodify学习 三:连接器
前置 连接概述 连接是由两个点之间创建的.Source和Target依赖属性是Point类型,通常绑定到连接器的Anchor点. 基本连接 库中所有连接的基类是BaseConnection,它派生自S ...
- Docker安装教程
这里介绍两种安装方法:centsOS安装和Ubuntu安装 CentOS安装 linux内核版本建议3.8以上,作者本人使用的是3.10:查看内核版本命令:uname -r 一般CentOS7以上都可 ...
- 将文件转换为文件流进行上传(例:通过HDMI进行传输)
package com.boottest.app; import org.apache.commons.codec.Charsets; import org.apache.http.HttpEntit ...
- 7.1 闲话-Erdős–Gallai 定理和哈基米算法
Erdős–Gallai 定理 前几天考试有一个建出最大流模型,转为最小割,然后模拟最小割的套路. 这一个套路并不是少见的.在 Gale-Ryser 定理和 Erdős–Gallai 定理的证明都体现 ...
- NIT GREAT NITYACKE DESTROYS THE UNIVERSE
线段树 一般线段树维护的东西是什么?设其维护的信息的半群 \((A,+)\),维护标记的半群 \((T,\times)\) 和一种运算 \(*\mapsto A*T\to A\). 要求 \((b+c ...
- 表治理-Iceberg小文件合并测试
总结 指标 合并前 合并后(因测试中多次合并,数据会偏多) 查询速度 246秒 13秒 表总大小 9.2G 26.4G 单个文件大小 1-25MB 60MB左右 metadata目录文件数 37 75 ...
- vue-element-template改为从后台获取菜单
一.后端接口获取菜单信息 1.返回数据样式 { "code": 20000, "data": [{ "menuId": "2000 ...
- Atcoder ABC390F Double Sum 3 题解 [ 绿 ] [ 贡献思维 ] [ 计数 ]
Double Sum 3:简单计数题. 思路 首先考虑单个区间的 \(f\) 值如何计算,显然等于值域上连续段的个数.那么我们进一步观察值域上连续段的性质,发现一个连续段的开头一定满足比开头小 \(1 ...
- NLLB 与 ChatGPT 双向优化:探索翻译模型与语言模型在小语种应用的融合策略
作者:来自 vivo 互联网算法团队- Huang Minghui 本文探讨了 NLLB 翻译模型与 ChatGPT 在小语种应用中的双向优化策略.首先介绍了 NLLB-200 的背景.数据.分词器和 ...