1.建立   netcore  mvc 项目。

2.startup.cs 中添加服务

 services.AddAuthorization(option=>
{
var requirements = new List<MyPermission>();
requirements.Add(new MyPermission() { Url = "/", Name = "admin" }); // 要有 / 开头
requirements.Add(new MyPermission() { Url = "/home/index", Name = "admin" });
requirements.Add(new MyPermission() { Url = "/default", Name = "root" });
option.AddPolicy("qgbplicy", policy =>
{
policy.Requirements.Add(new PermissionRequirement("/denied", requirements, ClaimTypes.Role));
}); }).AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(
option => {
option.AccessDeniedPath = "/home/Denied";
option.LoginPath = "/home/Login";
}
);
services.AddSingleton<IAuthorizationHandler, PermissionHandler>();
  app.UseAuthentication();

3.登录的controller:

  [AllowAnonymous]
[HttpPost]
public async Task<IActionResult> Login(string userName, string password, string returnUrl = null)
{ //用户标识
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
//如果是基于角色的授权策略,这里要添加用户
identity.AddClaim(new Claim(ClaimTypes.Name, "gsw"));
//如果是基于角色的授权策略,这里要添加角色
identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
if (returnUrl == null)
{
returnUrl = TempData["returnUrl"]?.ToString();
}
if (returnUrl != null)
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
} }

4.创建 PermissionHandler 类

    public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
//从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext; //是否经过验证
if (httpContext.User.Identity.IsAuthenticated)
{
var questUrl = httpContext.Request.Path.Value.ToLower();
//权限中是否存在请求的url
if (requirement.Permissions.Any(w => w.Url.ToLower() == questUrl))
{
var name = httpContext.User.Claims.SingleOrDefault(s => s.Type == requirement.ClaimType).Value;
//验证权限
if (requirement.Permissions.Any(w => w.Name == name))
{
context.Succeed(requirement);
}
else
{
//无权限跳转到拒绝页面
httpContext.Response.Redirect(requirement.DeniedAction);
}
}
else
{
context.Succeed(requirement);
}
}
return Task.CompletedTask;
}
}

自定义策略-简单实践 <一>的更多相关文章

  1. Security » Authorization » 基于自定义策略的授权

    Custom Policy-Based Authorization¶ 基于自定义策略的授权 98 of 108 people found this helpful Underneath the cov ...

  2. kafka原理和实践(二)spring-kafka简单实践

    系列目录 kafka原理和实践(一)原理:10分钟入门 kafka原理和实践(二)spring-kafka简单实践 kafka原理和实践(三)spring-kafka生产者源码 kafka原理和实践( ...

  3. Kubernetes集群的监控报警策略最佳实践

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/M2l0ZgSsVc7r69eFdTj/article/details/79652064 本文为Kub ...

  4. Thrift简单实践

    0.什么是RPC RPC(Remote Procedure Call - 远程过程调用),是通过网络从远程计算机上请求服务,而不需要了解底层网路技术的细节.简单点说,就是像调用本地服务(方法)一样调用 ...

  5. Java 异步处理简单实践

    Java 异步处理简单实践 http://www.cnblogs.com/fangfan/p/4047932.html 同步与异步 通常同步意味着一个任务的某个处理过程会对多个线程在用串行化处理,而异 ...

  6. Android 设计随便说说之简单实践(合理组合)

    上一篇(Android 设计随便说说之简单实践(模块划分))例举了应用商店设计来说明怎么做模块划分.模块划分主要依赖于第一是业务需求,具体是怎么样的业务.应用商店则包括两个业务,就是向用户展示appl ...

  7. JSP自定义标签——简单标签(2)

    在前一篇博客中,我们已经学习了自定义的简单标签的基本使用方法,这一篇我们来学习如何在简单标签中添加标签属性.对自定义标签添加一些属性,可以使我们的标签功能更加灵活和复用.例如前一篇博客使用简单标签来对 ...

  8. JSP自定义标签——简单标签(1)

    前面一篇博客介绍了自定义标签的传统标签使用方式,但是我们会发现,使用传统标签非常的麻烦,而且接口还多,现在传统标签基本都没用了,除了一些比较久的框架.Sun公司之后推出了一个新的标签使用方式,称之为简 ...

  9. c#中,委托Func的简单实践

    c# 委托Func的简单实践最近才真正的接触委托,所以针对Func类型的委托,做一个实践练习. 首先说一些我对委托的初级理解:"就是把方法当做参数,传进委托方法里". 我平时用到的 ...

随机推荐

  1. 【Linux】安装 node.js

    1.在 linux 上安装 node.js 有几种方式,这里 教的是最简单的一种,因为其他都比较坑. 2.先去 node.js 官网 获取到已经编译好的安装包的地址, 3.使用 wget 去下载上面获 ...

  2. delphi nethttpclient操作cookie

    delphi nethttpclient操作cookie unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysU ...

  3. Flutter移动电商实战 --(23)分类页_左侧类别导航制作

    自动生成dart类 https://javiercbk.github.io/json_to_dart/ 生成的代码 class Autogenerated { String code; String ...

  4. Projects: Linux scalability: Accept() scalability on Linux 惊群效应

    小结: 1.不必要的唤醒 惊群效应 https://github.com/benoitc/gunicorn/issues/792#issuecomment-46718939 https://www.c ...

  5. Swift 数据类型

    Swift 提供了非常丰富的数据类型,以下列出了常用了几种数据类型: Int 一般来说,你不需要专门指定整数的长度.Swift 提供了一个特殊的整数类型Int,长度与当前平台的原生字长相同: 在32位 ...

  6. in mind (不是 切记 的意思)

    Both Grunt and Gulp.js perform these automation tasks particularly well, although Gulp.js has the ed ...

  7. c++ map multimap操作

    #include <iostream>#include <map>#include <string> using namespace std; int main() ...

  8. PAT 甲级 1027 Colors in Mars (20 分)(简单,进制转换)

    1027 Colors in Mars (20 分)   People in Mars represent the colors in their computers in a similar way ...

  9. Hadoop常用命令介绍

    本文主要介绍 Hadoop 常用的命令. test命令 用于检测文件或目录是否存在,判断文件或目录大小. -test -[defsz] <path> : Answer various qu ...

  10. 一条语句kill 多条mysql语句

    If information_schema.processlist doesn’t exist on your version of MySQL, this works in a linux scri ...