在.Net Core 中使用AuthorizeFilter或者ActionFilterAttribute来实现登录权限验证和授权

一、AuthorizeFilter

新建授权类AllowAnonymous继承AuthorizeFilter,IAllowAnonymousFilter

public class AllowAnonymous : AuthorizeFilter, IAllowAnonymousFilter
{ }

新建拦截类继承AuthorizeFilter

public class LoginAuthorzation : AuthorizeFilter
{ }

在拦截类里加入处理请求的方法

        /// <summary>
/// 请求验证,当前验证部分不要抛出异常,ExceptionFilter不会处理
/// </summary>
/// <param name="context">请求内容信息</param>
public override async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (IsHaveAllow(context.Filters))
{
return;
} //解析url
// {/ Home / Index}
var url = context.HttpContext.Request.Path.Value;
if (string.IsNullOrWhiteSpace(url))
{
return;
} var list = url.Split("/");
if (list.Length<=||url=="/")
{
return;
}
var controllerName = list[].ToString().Trim();
var actionName = list[].ToString().Trim(); //验证
var flag=PowerIsTrue.IsHavePower(controllerName, actionName);
if (flag.Item1!=)
{ context.Result = new RedirectResult("/Home/Index");
}
} //判断是否不需要权限 public static bool IsHaveAllow(IList<IFilterMetadata> filers)
{
for (int i = ; i < filers.Count; i++)
{
if (filers[i] is IAllowAnonymousFilter)
{
return true;
}
}
return false; }

新建一个业务逻辑判断的类

public static (int,string) IsHavePower(string controllerName,string actionName)
{ return (,"通过"); }

在Startup注册

 services.AddMvc(options =>
{ options.Filters.Add<LoginAuthorzation>(); // 添加身份验证过滤器 }

 

context.HttpContext.Request.Path.Value   获取请求过来的url

二、ActionFilterAttribute

创建权限判断类继承ActionFilterAttribute

public class ActionFilterAttributeLogin: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext) {
var isDefined = false;
var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
.Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)));
}
if (isDefined) return;
if (string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Query["LoginInfo"].ToString()))
{
var item = new ContentResult();
item.Content = "没得权限"; filterContext.Result = new RedirectResult("/Account/Login");
}
base.OnActionExecuting(filterContext);
} public class NoPermissionRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext); } }
}

在Startup注册

services.AddMvc(options =>
{
options.Filters.Add<ActionFilterAttributeLogin>(); // 添加身份验证过滤器 -- 菜单操作权限 }

filterContext.ActionDescriptor as ControllerActionDescriptor    获取请求进来的控制器与方法

controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)

.Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)))      判断请求的控制器和方法有没有加上NoPermissionRequiredAttribute(不需要权限)

 

string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Query["LoginInfo"].ToString())     判断请求头是否有标识


  欢迎大家扫描下方二维码,和我一起学习更多的知识

.Net Core 权限验证与授权(AuthorizeFilter、ActionFilterAttribute)的更多相关文章

  1. 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分

    原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...

  2. 从零搭建一个IdentityServer——聊聊Asp.net core中的身份验证与授权

    OpenIDConnect是一个身份验证服务,而Oauth2.0是一个授权框架,在前面几篇文章里通过IdentityServer4实现了基于Oauth2.0的客户端证书(Client_Credenti ...

  3. C# MVC权限验证

    前言 之前一直没怎么接触过权限验证这块,刚好公司老平台改版,就有了这篇权限验证.此篇文章大致讲解下 精确到按钮级别的验证如何实现.以及权限验证设计的参考思路(菜鸟一枚,大神勿喷). 在开发大项目的时候 ...

  4. .NET Core微服务之基于Ocelot+IdentityServer实现统一验证与授权

    Tip: 此篇已加入.NET Core微服务基础系列文章索引 一.案例结构总览 这里,假设我们有两个客户端(一个Web网站,一个移动App),他们要使用系统,需要通过API网关(这里API网关始终作为 ...

  5. .Net Core权限认证基于Cookie的认证&授权.Scheme、Policy扩展

    在身份认证中,如果某个Action需要权限才能访问,最开始的想法就是,哪个Action需要权限才能访问,我们写个特性标注到上面即可,[TypeFilter(typeof(CustomAuthorize ...

  6. 学学dotnet core中的身份验证和授权-1-概念

    前言 身份验证: Authentication 授权: Authorization net core 中的身份验证和授权这两个部分,是相辅相成的.当初我在学在部分的时候,是看的 net core 官网 ...

  7. mvc 4 ActionFilterAttribute 特性,进行权限验证

    权限验证: /// <summary> /// 管理员身份验证 /// </summary> public class BasicAuthenticationAttribute ...

  8. Asp.net Core, 基于 claims 实现权限验证 - 引导篇

    什么是Claims? 这个直接阅读其他大神些的文章吧,解释得更好. 相关文章阅读: http://www.cnblogs.com/JustRun1983/p/4708176.html http://w ...

  9. .NET CORE TOKEN 权限验证

    原文:.NET CORE TOKEN 权限验证 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/u012601647/article/details/ ...

随机推荐

  1. NSURLSession 所有的都在这里(一)

    这篇文章会有什么? 在这篇文章中把NSURLSession.h文件集体梳理一遍,把里面的每个属性.代理和方法都拿出来说说,通过这篇文章我相信对于NSURLSession这一块的东西会梳理的比较全面一点 ...

  2. 微信小程序入门三实战

    微信小应用借鉴了很多web的理念,但是其与传统的webApp.微信公共号这些BS架构不同,他是CS架构,是客户端的程序 小程序开发实战--豆瓣电影 项目配置 -在app.jsop中进行简单配置 --n ...

  3. 我们常说的 CAS 自旋锁是什么

    CAS(Compare and swap),即比较并交换,也是实现我们平时所说的自旋锁或乐观锁的核心操作. 它的实现很简单,就是用一个预期的值和内存值进行比较,如果两个值相等,就用预期的值替换内存值, ...

  4. (汇总)os模块以及shutil模块对文件的操作

    ''' # os 模块 os.sep 可以取代操作系统特定的路径分隔符.windows下为 '\\' os.name 字符串指示你正在使用的平台.比如对于Windows,它是'nt',而对于Linux ...

  5. Java动态代理(一)

    好久没有动笔了,最近想巩固一下自己的基础知识,最近听到一同事问为什么JDK动态代理不能代理类,一听感觉懵逼呀!自己好像也不能很好的描述出来,所以想用2篇文章来复习一下动态代理知识: 一.什么是静态代理 ...

  6. 用shell处理以下内容 1、按单词出现频率降序排序! 2、按字母出现频率降序排序! the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support

    此题目有多种解法,sed.awk.tr等等,都可以解决此题,命令运用灵活多变. 编写shell脚本no_20.sh 解法1: #!/bin/bash ###-------------CopyRight ...

  7. Spring @Conditional注解的使用

    Spring Boot的强大之处在于使用了Spring 4框架的新特性:@Conditional注释,此注释使得只有在特定条件满足时才启用一些配置. 下面来介绍如何使用Condition 首先写一个类 ...

  8. Vue数据双向绑定原理及简单实现

    嘿,Goodgirl and GoodBoy,点进来了就看完点个赞再go. Vue这个框架就不简单介绍了,它最大的特性就是数据的双向绑定以及虚拟dom.核心就是用数据来驱动视图层的改变.先看一段代码. ...

  9. MySQL中group_concat函数深入理解

    本文通过实例介绍了MySQL中的group_concat函数的使用方法,比如select group_concat(name) . 一.MySQL中group_concat函数 完整的语法如下: gr ...

  10. javascript系列2 -- 闭包详解

    转发请标明来源:http://www.cnblogs.com/johnhou/p/javascript.html  请尊重笔者的劳动成果  --John Hou 今天我们从内存结构上来讲解下 java ...