ABP框架源码学习之授权逻辑
asp.net core的默认的几种授权方法参考“雨夜朦胧”的系列博客,这里要强调的是asp.net core mvc中的授权和asp.net mvc中的授权不一样,建议先看前面“雨夜朦胧”的博客。
Abp中Controller里面用到的权限验证类为:AbpMvcAuthorizeAttribute,ApplicationService里面用到的权限验证类为:AbpAuthorizeAttribute(见下图)。


AbpMvcAuthorizeAttribute和AbpAuthorizeAttribute这两个类全部继承自IAbpAuthorizeAttribute(重要!!!),下面是这两个类的源码。
namespace Abp.Authorization
{
/// <summary>
/// This attribute is used on a method of an Application Service (A class that implements <see cref="IApplicationService"/>)
/// to make that method usable only by authorized users.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class AbpAuthorizeAttribute : Attribute, IAbpAuthorizeAttribute
{
/// <summary>
/// A list of permissions to authorize.
/// </summary>
public string[] Permissions { get; } /// <summary>
/// If this property is set to true, all of the <see cref="Permissions"/> must be granted.
/// If it's false, at least one of the <see cref="Permissions"/> must be granted.
/// Default: false.
/// </summary>
public bool RequireAllPermissions { get; set; } /// <summary>
/// Creates a new instance of <see cref="AbpAuthorizeAttribute"/> class.
/// </summary>
/// <param name="permissions">A list of permissions to authorize</param>
public AbpAuthorizeAttribute(params string[] permissions)
{
Permissions = permissions;
}
}
}
namespace Abp.AspNetCore.Mvc.Authorization
{
/// <summary>
/// This attribute is used on an action of an MVC <see cref="Controller"/>
/// to make that action usable only by authorized users.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class AbpMvcAuthorizeAttribute : AuthorizeAttribute, IAbpAuthorizeAttribute
{
/// <inheritdoc/>
public string[] Permissions { get; set; } /// <inheritdoc/>
public bool RequireAllPermissions { get; set; } /// <summary>
/// Creates a new instance of <see cref="AbpMvcAuthorizeAttribute"/> class.
/// </summary>
/// <param name="permissions">A list of permissions to authorize</param>
public AbpMvcAuthorizeAttribute(params string[] permissions)
{
Permissions = permissions;
}
}
}
重点来啦!!!
namespace Abp.AspNetCore.Mvc.Authorization
{
public class AbpAuthorizationFilter : IAsyncAuthorizationFilter, ITransientDependency
{
public ILogger Logger { get; set; } private readonly IAuthorizationHelper _authorizationHelper;
private readonly IErrorInfoBuilder _errorInfoBuilder;
private readonly IEventBus _eventBus; public AbpAuthorizationFilter(
IAuthorizationHelper authorizationHelper,
IErrorInfoBuilder errorInfoBuilder,
IEventBus eventBus)
{
_authorizationHelper = authorizationHelper;
_errorInfoBuilder = errorInfoBuilder;
_eventBus = eventBus;
Logger = NullLogger.Instance;
} public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
// 判断context中是否有继承IAllowAnoymousFilter,有则跳出方法即验证成功
if (context.Filters.Any(item => item is IAllowAnonymousFilter))
{
return;
}
//判断是否是Controller,具体方法见下面第一张截图
if (!context.ActionDescriptor.IsControllerAction())
{
return;
} //TODO: Avoid using try/catch, use conditional checking
try
{
await _authorizationHelper.AuthorizeAsync(
context.ActionDescriptor.GetMethodInfo(),
context.ActionDescriptor.GetMethodInfo().DeclaringType
);
}
catch (AbpAuthorizationException ex)
{
Logger.Warn(ex.ToString(), ex); _eventBus.Trigger(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
{
context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true))
{
StatusCode = context.HttpContext.User.Identity.IsAuthenticated
? (int) System.Net.HttpStatusCode.Forbidden
: (int) System.Net.HttpStatusCode.Unauthorized
};
}
else
{
context.Result = new ChallengeResult();
}
}
catch (Exception ex)
{
Logger.Error(ex.ToString(), ex); _eventBus.Trigger(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
{
context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex)))
{
StatusCode = (int) System.Net.HttpStatusCode.InternalServerError
};
}
else
{
//TODO: How to return Error page?
context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError);
}
}
}
}
}




拓展:当我们有某个业务需要用到AOP时,但又不想使用一些第三方框架,我们就可以借鉴上面的方法,定义一个特性,然后定义一个Filter,在Filter里面判断Controller等是否使用这些特性,并且特性的属性是否符合我们的需求,最后在Startup里面AddMvc时将这个Filter添加到FilterCollection里面。例如下图,自动验证AntiforgeryToken

ABP框架源码学习之授权逻辑的更多相关文章
- ABP框架源码学习之修改默认数据库表前缀或表名称
ABP框架源码学习之修改默认数据库表前缀或表名称 1,源码 namespace Abp.Zero.EntityFramework { /// <summary> /// Extension ...
- Golang源码学习:调度逻辑(二)main goroutine的创建
接上一篇继续分析一下runtime.newproc方法. 函数签名 newproc函数的签名为 newproc(siz int32, fn *funcval) siz是传入的参数大小(不是个数):fn ...
- 集合框架源码学习之ArrayList
目录: 0-0-1. 前言 0-0-2. 集合框架知识回顾 0-0-3. ArrayList简介 0-0-4. ArrayList核心源码 0-0-5. ArrayList源码剖析 0-0-6. Ar ...
- CI框架源码学习笔记1——index.php
做php开发一年多了,陆陆续续用过tp/ci/yii框架,一直停留在只会使用的层面上,关于框架内部的结构实际上是不甚了解的.为了深入的学习,决定把CI框架的源码从头到尾的学习一下, 主要因为CI框架工 ...
- axel源码学习(0)——程序逻辑
axel简介 axel是一个命令行下的轻量级http/ftp 下载加速工具,支持多线程下载和断点续传,支持从多个镜像下载同一文件. axel的用法如下: 图 0.1 axel usage axel 粗 ...
- 集合框架源码学习之HashMap(JDK1.8)
目录: 0-1. 简介 0-2. 内部结构分析 0-2-1. JDK18之前 0-2-2. JDK18之后 0-3. LinkedList源码分析 0-3-1. 构造方法 0-3-2. put方法 0 ...
- 集合框架源码学习之LinkedList
0-1. 简介 0-2. 内部结构分析 0-3. LinkedList源码分析 0-3-1. 构造方法 0-3-2. 添加add方法 0-3-3. 根据位置取数据的方法 0-3-4. 根据对象得到索引 ...
- CI框架源码学习笔记7——Utf8.php
愉快的清明节假期结束了,继续回到CI框架学习.这一节我们来看看Utf8.php文件,它主要是用来做utf8编码,废话不多说,上代码. class CI_Utf8 { /** * Class const ...
- CI框架源码学习笔记2——Common.php
上一节我们最后说到了CodeIgniter.php,可是这一节的标题是Common.php,有的朋友可能会觉得很奇怪.事实上,CodeIgniter.php其实包含了ci框架启动的整个流程. 里面引入 ...
随机推荐
- Spring测试框架JUnit4.4 还蛮详细的
TestContext 可以运行在 JUnit 3.8.JUnit 4.4.TestNG 等测试框架下. Spring的版本2.5+JUnit4.4+log4j1.2.12 @RunWith(Spri ...
- Linuxc - 标准输入流、标准输出流、标准错误流
输入流stdin默认是键盘,输出流stdout默认是显示器,错误流stderr #include <stdio.h> int main() { printf("请输入选择的数字: ...
- VM安装Ubuntu问题合集(无法联网、中文界面设置、中文输入法etc)
经常使用VM安装Ubuntu,安装系统的步骤跟着系统提示一步步下来就行,但总是遇到一些问题,这里记录一下常遇到的问题,以及自己解决的办法: 1.无法联网: 状况:Ubuntu不能联网,联网地方一直在闪 ...
- 存储管理工具StorageExplorer的基本使用
本文主要介绍Azure StorageExplorer工具的安装及基本使用 1.打开Azure官方链接:https://www.azure.cn/downloads/ 2.按照向导进行安装 3.可以通 ...
- junit4X系列--Exception
原文出处:http://www.blogjava.net/DLevin/archive/2012/11/02/390684.html.感谢作者的无私分享. 说来惭愧,虽然之前已经看过JUnit的源码了 ...
- Linux指令--traceroute,netstat,ss
通过traceroute我们可以知道信息从你的计算机到互联网另一端的主机是走的什么路径.当然每次数据包由某一同样的出发点(source)到达某一同样的目的地(destination)走的路径可能会不一 ...
- win10预览版无开始菜单解决方案
1.按下Win+R键打开“运行”程序,键入gpedit.msc 回车以打开本地组策略编辑器 2.调到图示位置将windows设置->安全设置->本地策略->安全选项->“用户账 ...
- 4个强大的Linux服务器监控工具[转]
本文介绍了一些可以用来监控网络使用情况的Linux命令行工具.这些工具可以监控通过网络接口传输的数据,并测量目前哪些数据所传输的速度.入站流量和出站流量分开来显示. 一些命令可以显示单个进程所使用的带 ...
- Ubuntu16.04下的2009q3交叉编译工具链的搭建
环境搭建: 1.下载arm-2009q3.tar.bz2源码. 百度云链接 密码: rbui 2.将arm-2009q3.tar.bz2拷贝到/usr/local/arm(没有该目录就 ...
- linux服务器配置pyspark解决py4j报错等问题
1.下载spark,python包 略 2.环境变量配置 打开 ~/.bashrc配置文件 如图添加下列环境变量及path 3.退出配置文件,输入 source ~/.bashrc 来执行你添加的一些 ...