本文目录

Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主,当然如果说webapi或者其他的分布式解决方案授权,也容易就可以实现单点登录都非常的简单,可以使用现成的IdentityServer框架或者自定义实现动非常方便和干净,如果你在运行示例代码的时候未达到预期效果,请把文章拉到结尾寻找答案。

本文示例代码下载,github我这访问不了,暂且直接上传博客园存储了。

准备

    1. 创建一个名为AuthorizationForoNetCore的(web)解决方案,选择Empty模板
    2. 添加相关nuget包引用Microsoft.AspNetCore.Mvc(选择最新版本)
    3. 编辑Startup.cs文件,添加mvcservice并进行默认路由配置
      1. public class Startup
      2. {
      3. public void ConfigureServices(IServiceCollection services)
      4. {
      5. services.AddMvc();
      6. }
      7.  
      8. public void Configure(IApplicationBuilder app)
      9. {
      10. app.UseMvc(routes =>
      11. {
      12. routes.MapRoute(
      13. name: "default",
      14. template: "{controller=Home}/{action=Index}/{id?}");
      15. });
      16. }
      17. }
    4. 添加Controllers文件夹,添加HomeContrller 

      1. public class HomeController : Controller
      2. {
      3. public IActionResult Index()
      4. {
      5. return View();
      6. }
      7. }
    5. 创建Views/Home文件夹,并添加Index(Action)对应的Index.cshtml文件

      1. <!--Index.cshtml-->
      2. 假如生活欺骗了你
      3. 假如生活欺骗了你,
      4. 不要悲伤,不要心急!
      5. 忧郁的日子里须要镇静:
      6. 相信吧,快乐的日子将会来临!   

使用Authorization

  1. 添加相关nuget包(均使用最新版本)
    1. Microsoft.AspNetCore.Authorization
    2. Microsoft.AspNetCore.Authentication.Cookies
  2. 在ConfigureServices()方法中添加对应服务:  services.AddAuthorization()
  3. Index(Action)方法上添加 [Authorize] 特性,毫无疑问,添加后执行dotnet run 指令后后会返回401的授权码,那么接着操作
  4. 编辑Startup.csConfigureapp.UseMvc()方法之前,我们添加一个cookie 中间件,用于持久化请求管道中的身份配置信息
    1. app.UseCookieAuthentication(new CookieAuthenticationOptions
    2. {
    3. AuthenticationScheme = "MyCookieMiddlewareInstance",
    4. LoginPath = new PathString("/Account/Unauthorized/"),
    5. AccessDeniedPath = new PathString("/Account/Forbidden/"),
    6. AutomaticAuthenticate = true,
    7. AutomaticChallenge = true
    8. });  
  5. tip:相关配置参数细节请参阅:https://docs.asp.net/en/latest/security/authentication/cookie.html

  6. 添加Controllers/Account文件夹,添加 AccountController.cs 控制器文件,实现上述指定的方法,可能这里你会疑惑,为什么文档里不是一个 /Account/Login 这类的,文档说了别较真,这就是个例子而已,继续你就明白了。
  7. 添加并实现上述中间件重定向的action 方法如下,你可以看到其实Unauthorized方法模拟实现了登陆的过程。tip:假如你添加Unauthorized视图,并且没有该不实现模拟登陆,那么运行你会直接看到 Unauthorized.cshtml 的内容,这里我们不需要添加该视图,仅作说明。
    1. public class AccountController : Controller
    2. {
    3. public async Task<IActionResult> Unauthorized(string returnUrl = null)
    4. {
    5. List<Claim> claims = new List<Claim>();
    6. claims.Add(new Claim(ClaimTypes.Name, "halower", ClaimValueTypes.String, "https://www.cnblogs.com/rohelm"));
    7. var userIdentity = new ClaimsIdentity("管理员");
    8. userIdentity.AddClaims(claims);
    9. var userPrincipal = new ClaimsPrincipal(userIdentity);
    10. await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", userPrincipal,
    11. new AuthenticationProperties
    12. {
    13. ExpiresUtc = DateTime.UtcNow.AddMinutes(),
    14. IsPersistent = false,
    15. AllowRefresh = false
    16. });
    17.  
    18. if (Url.IsLocalUrl(returnUrl))
    19. {
    20. return Redirect(returnUrl);
    21. }
    22. else
    23. {
    24. return RedirectToAction("Index", "Home");
    25. }
    26. }
    27.  
    28. public IActionResult Forbidden()
    29. {
    30. return View();
    31. }
    32. }
  8. 编辑 Home/Index.schtml

    1. @using System.Security.Claims;
    2.  
    3. @if (User.Identities.Any(u => u.IsAuthenticated))
    4. {
    5. <h1>
    6. 欢迎登陆 @User.Identities.First(u => u.IsAuthenticated).FindFirst(ClaimTypes.Name).Value
    7. </h1>
    8. <h2>所使用的身份验证的类型:@User.Identity.AuthenticationType</h2>
    9. }
    10. <article>
    11. 假如生活欺骗了你<br />
    12. 假如生活欺骗了你<br />
    13. 不要悲伤,不要心急<br />
    14. 忧郁的日子里须要镇静<br />
    15. 相信吧,快乐的日子将会来临  
    16. </article>
  9. 运行代码你会看到如下结果(程序获取我们提供的由issuer发布claims并展示在视图中,后续会检查Claims看他们是否匹配)

使用全局授权策略

  1. 去除Home/Index (Action)上的  [Authorize]  特性
  2. 添加 Views/Account/Forbidden.cshtml 页面,内容为 <h1>拒绝访问</h1>
  3. 修改 ConfigureServices 方法中的 services.AddMvc() 使用它的 AddMvc(this IServiceCollection services, Action<MvcOptions> setupAction) 重载
  4. 运行查看结果,你会发现这几乎成了一个无限的重定向从而造成错误,因为每个页面都需要授权。
  5. 为 AccountController 添加 [AllowAnonymous] 特性,启动匿名访问,再次运行项目,查看结果
  6. 结果就是重定向到了 Forbidden.cshtml 页面

使用角色授权

  1. 在 HomeController 上添加 [Authorize(Roles = "Administrator")] 特性
  2. 在模拟登陆处( Unauthorized方法中 )添加角色说明的身份信息条目:
  3. claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, "https://www.cnblogs.com/rohelm"));
  4. 运行项目查看结果

可以使用中你会发现Asp.net Core安全验证方面较以往的版本最大的改变就是全部采用中间件的方式进行验证授权,并很好的使用了Policy (策略)这个概念,下那么继续~。

基于声明的授权

  1. 返回Startup.cs,修改 services.AddAuthorization() 方法如下:

    1. services.AddAuthorization(options =>
    2. {
    3. options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("EmployeeNumber"));
    4. });
  2. 修改HomeController上的特性,添加 [Authorize(Policy = "EmployeeOnly")]
  3. 运行项目查看结果,发现被拒绝了
  4. 在模拟登陆处 Unauthorize方法添加:
    1. claims.Add(", ClaimValueTypes.String, "http://www.cnblogs.com/rohelm"));
  5. goto 3.
  6. 多重策略的应用,与之前的版本几乎一样,例如本次修改的结果可以为:
    1. [Authorize(Roles = "Administrator")]
    2. public class HomeController:Controller
    3. {
    4. [Authorize(Policy = "EmployeeOnly")]
    5. public IActionResult Index()
    6. {
    7. return View();
    8. }
    9. } 
  7. 详情请参阅:https://docs.asp.net/en/latest/security/authorization/claims.html的说明

自定义授权策略

自定义授权策略的实现,包括实现一个 IAuthorizationRequirement 的Requirement,和实现 AuthorizationHandler<TRequirement> 的处理器,这里使用文档

https://docs.asp.net/en/latest/security/authorization/policies.html中的Code。

  1. 添加 MinimumAgeHandler 处理器实现

    1. public class MinimumAgeRequirement: AuthorizationHandler<MinimumAgeRequirement>, IAuthorizationRequirement
    2. {
    3. int _minimumAge;
    4.  
    5. public MinimumAgeRequirement(int minimumAge)
    6. {
    7. _minimumAge = minimumAge;
    8. }
    9.  
    10. protected override void Handle(AuthorizationContext context, MinimumAgeRequirement requirement)
    11. {
    12. if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
    13. {
    14. return;
    15. }
    16.  
    17. var dateOfBirth = Convert.ToDateTime(
    18. context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value);
    19.  
    20. int calculatedAge = DateTime.Today.Year - dateOfBirth.Year;
    21. if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge))
    22. {
    23. calculatedAge--;
    24. }
    25.  
    26. if (calculatedAge >= _minimumAge)
    27. {
    28. context.Succeed(requirement);
    29. }
    30. }
    31. }
  2. 在 AddAuthorization  中添加一个名为Over21的策略
    1. options.AddPolicy()));
  3. 在HomeController上应用该策略  [Authorize(Policy = "Over21")]
  4. 在 Unauthorized 函数中添加对应的声明信息条目 claims.Add(new Claim(ClaimTypes.DateOfBirth, "1900-01-01", ClaimValueTypes.Date));
  5. 修改时间(例如小于21岁的生日,2000-01-01)并运行调试,查看结果

对一个Requirement应用多个处理器

tip:上面的演示,我们使用了一个同时实现AuthorizationHandler<MinimumAgeRequirement>, IAuthorizationRequirement的MinimumAgeRequirement来做演示,但是如果一个Requirement徐要实现多个处理器就需要分开写了,原因很简单,这里无法实现类的多重继承。

下面我们实现一个使用Token登陆的需求

  1. 添加一个LoginRequirement的需求

    1. public class LoginRequirement: IAuthorizationRequirement
    2. {
    3. }
  2. 添加一个使用用户名密码登陆的处理器
    1. public class HasPasswordHandler : AuthorizationHandler<LoginRequirement>
    2. {
    3. protected override void Handle(AuthorizationContext context, LoginRequirement requirement)
    4. {
    5. if (!context.User.HasClaim(c => c.Type == "UsernameAndPassword" && c.Issuer == "http://www.cnblogs.com/rohelm"))
    6. return;
    7. context.Succeed(requirement);
    8. }
    9. }
  3. 在一些场景中我们也会使用发放访问令牌的方式让用户登陆
    1. public class HasAccessTokenHandler : AuthorizationHandler<LoginRequirement>
    2. {
    3. protected override void Handle(AuthorizationContext context, LoginRequirement requirement)
    4. {
    5. if (!context.User.HasClaim(c => c.Type == "AccessToken" && c.Issuer == "http://www.cnblogs.com/rohelm"))
    6. return;
    7.  
    8. var toeknExpiryIn = Convert.ToDateTime(context.User.FindFirst(c => c.Type == "AccessToken" && c.Issuer == "http://www.cnblogs.com/rohelm").Value);
    9.  
    10. if (toeknExpiryIn > DateTime.Now)
    11. {
    12. context.Succeed(requirement);
    13. }
    14. }
    15. }
  4. 在 AddAuthorization  中添加一个名为CanLogin的策略
    1. options.AddPolicy("CanLogin", policy => policy.Requirements.Add(new LoginRequirement()));
  5. 注册自定义策略
    1. services.AddSingleton<IAuthorizationHandler, HasPasswordHandler>();
    2. services.AddSingleton<IAuthorizationHandler, HasAccessTokenHandler>();
  6. 在Unauthorized 函数中添加对应的声明信息条目
    1. claims.Add(", ClaimValueTypes.String, "http://www.cnblogs.com/rohelm")); // 测试切换登陆声明方式 // claims.Add(new Claim("AccessToken", DateTime.Now.AddMinutes(1).ToString(), ClaimValueTypes.String, "http://www.cnblogs.com/rohelm"));
  7. 在HomeController上应用该策略  [Authorize(Policy = "CanLogin")]
  8. 运行并查看结果。

基于资源的Requirements

在实际开发者中,除了基于用户的授权验证外,通过我们也会遇到针对一些资源的授权限制,例如有的人可以编辑文档,有的人只能查看文档,由此引出该话题

https://docs.asp.net/en/latest/security/authorization/resourcebased.html

  1. 定义一个Document类

    1. public class Document
    2. {
    3. public int Id { get; set; }
    4. public string Author { get; set; }
    5. }
  2. 定义Document仓储接口
    1. public interface IDocumentRepository
    2. {
    3. IEnumerable<Document> Get();
    4. Document Get(int id);
    5. }
  3. 模拟实现上述接口
    1. public class FakeDocumentRepository : IDocumentRepository
    2. {
    3. static List<Document> _documents = new List<Document> {
    4. , Author = "halower" },
    5. , Author = "others" }
    6. };
    7. public IEnumerable<Document> Get()
    8. {
    9. return _documents;
    10. }
    11.  
    12. public Document Get(int id)
    13. {
    14. return _documents.FirstOrDefault(d => d.Id == id);
    15. }
    16. }
  4. 注册接口实现类
    1. services.AddSingleton<IDocumentRepository, FakeDocumentRepository>();
  5. 创建一个 DocumentController 并修改为如下内容
    1. public class DocumentController : Controller
    2. {
    3. IDocumentRepository _documentRepository;
    4.  
    5. public DocumentController(IDocumentRepository documentRepository)
    6. {
    7. _documentRepository = documentRepository;
    8. }
    9.  
    10. public IActionResult Index()
    11. {
    12. return View(_documentRepository.Get());
    13. }
    14.  
    15. public IActionResult Edit(int id)
    16. {
    17. var document = _documentRepository.Get(id);
    18.  
    19. if (document == null)
    20. return new NotFoundResult();
    21.  
    22. return View(document);
    23. }
    24. }
  6. 添加对应 Index.cshtml  视图文件
    1. @model IEnumerable<AuthorizationForoNetCore.Modles.Document>
    2.  
    3. <h1>文档列表</h1>
    4. @foreach (var document in Model)
    5. {
    6. <p>
    7. @Html.ActionLink("文档 #" + document.Id, "编辑", new { id = document.Id })
    8. </p>
    9. }
  7. 添加对应的 Edit.cshtml 视图文件
    1. @model AuthorizationForoNetCore.Modles.Document
    2.  
    3. <h1>文档 #@Model.Id</h1>
    4. <h2>作者: @Model.Author</h2>
  8. 定义EditRequirement
    1. public class EditRequirement : IAuthorizationRequirement
    2. {
    3. }
  9. 添加对应的编辑文档处理器
    1. public class DocumentEditHandler : AuthorizationHandler<EditRequirement, Document>
    2. {
    3. protected override void Handle(AuthorizationContext context, EditRequirement requirement, Document resource)
    4. {
    5. if (resource.Author == context.User.FindFirst(ClaimTypes.Name).Value)
    6. {
    7. context.Succeed(requirement);
    8. }
    9. }
    10. }
  10. 在 ConfigureServices() 方法中注册处理器实现
    1. services.AddSingleton<IAuthorizationHandler, DocumentEditHandler>();
  11. 由于对于文档的授权服务仅仅反正在操作方法的内部,因此我们需要直接注入 IAuthorizationService 对象并在需要的Action内部直接处理
    1. public class DocumentController : Controller
    2. {
    3. IDocumentRepository _documentRepository;
    4. IAuthorizationService _authorizationService;
    5.  
    6. public DocumentController(IDocumentRepository documentRepository, IAuthorizationService authorizationService)
    7. {
    8. _documentRepository = documentRepository;
    9. _authorizationService = authorizationService;
    10. }
    11.  
    12. public IActionResult Index()
    13. {
    14. return View(_documentRepository.Get());
    15. }
    16.  
    17. public async Task<IActionResult> Edit(int id)
    18. {
    19. var document = _documentRepository.Get(id);
    20.  
    21. if (document == null)
    22. return new NotFoundResult();
    23.  
    24. if (await _authorizationService.AuthorizeAsync(User, document, new EditRequirement()))
    25. {
    26. return View(document);
    27. }
    28. else
    29. {
    30. return new ChallengeResult();
    31. }
    32. }
    33. }
  12. 运行查看结果

在视图中进行授权

问题来了额,上面示例的视图中怎么做限制了,那就继续了

1.使用  @inject 命令注入 AuthorizationService

2.应用该上述同样策略,做简单修改

  1. @using Microsoft.AspNetCore.Authorization
  2. @model IEnumerable<AuthorizationForoNetCore.Modles.Document>
  3. @inject IAuthorizationService AuthorizationService
  4. @using AuthorizationForoNetCore.Policy
  5. <h1>文档列表</h1>
  6. @{
  7. var requirement = new EditRequirement();
  8. foreach (var document in Model)
  9. {
  10. if (await AuthorizationService.AuthorizeAsync(User, document, requirement)) {
  11. <p>
  12. @Html.ActionLink("文档 #" + document.Id, "编辑", new { id = document.Id })
  13. </p>
  14. }
  15. }
  16. }

请在运行时清理Cookie,或者在试验时直接暂时禁用

之前写的一个插件,谁有时间帮升级支持下asp.net Core:https://github.com/halower/JqGridForMvc

教你实践ASP.NET Core Authorization的更多相关文章

  1. [转]教你实践ASP.NET Core Authorization

    本文转自:http://www.cnblogs.com/rohelm/p/Authorization.html 本文目录 Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主, ...

  2. ASP.NET Core Authorization

    ASP.NET Core Authorization 本文目录 Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主,当然如果说webapi或者其他的分布式解决方案授权,也容易 ...

  3. win10 uwp 手把手教你使用 asp dotnet core 做 cs 程序

    本文是一个非常简单的博客,让大家知道如何使用 asp dot net core 做后台,使用 UWP 或 WPF 等做前台. 本文因为没有什么业务,也不想做管理系统,所以看到起来是很简单. Visua ...

  4. 一篇文章教你学会ASP.Net Core LINQ基本操作

    一篇文章教你学会ASP.Net Core LINQ基本操作 为什么要使用LINQ LINQ中提供了很多集合的扩展方法,配合lambda能简化数据处理. 例如我们想要找出一个IEnumerable< ...

  5. ASP.NET Core & Docker 实战经验分享

    一.前言 最近一直在研究和实践ASP.NET Core.Docker.持续集成.在ASP.NET Core 和 Dcoker结合下遇到了一些坑,在此记录和分享,希望对大家有一些帮助. 二.中间镜像 我 ...

  6. Building microservices with ASP.NET Core (without MVC)(转)

    There are several reasons why it makes sense to build super-lightweight HTTP services (or, despite a ...

  7. win10 uwp 使用 asp dotnet core 做图床服务器客户端

    原文 win10 uwp 使用 asp dotnet core 做图床服务器客户端 本文告诉大家如何在 UWP 做客户端和 asp dotnet core 做服务器端来做一个图床工具   服务器端 从 ...

  8. 《ASP.NET Core应用开发入门教程》与《ASP.NET Core 应用开发项目实战》正式出版

    “全书之写印,实系初稿.有时公私琐务猬集,每写一句,三搁其笔:有时兴会淋漓,走笔疾书,絮絮不休:有时意趣萧索,执笔木坐,草草而止.每写一段,自助覆阅,辄摇其首,觉有大不妥者,即贴补重书,故剪刀浆糊乃不 ...

  9. ASP.NET Core OceLot 微服务实践

    1.OceLot中间件介绍 在传统的BS应用中,随着业务需求的快速发展变化,需求不断增长,迫切需要一种更加快速高效的软件交付方式.微服务可以弥补单体应用不足,是一种更加快速高效软件架构风格.单体应用被 ...

随机推荐

  1. MS10-087微软OFFICE漏洞【参考拿机模拟】

    [声明:以下测试仅仅为了学习用途,模仿尝试与博主无关] 工  具:metasploit 目标机:windows xp sp3  步骤: 1.使用msf创建特殊代码的doc文档 命令: msfconso ...

  2. mysql获取一个表中的下一个自增(id)值的方法

    SELECT Auto_increment FROM information_schema.`TABLES` WHERE Table_Schema='数据库名' AND table_name = '表 ...

  3. php打印中文乱码

    php文档的文本格式都设置成 utf-8 格式 在代码中添加 header("content-type:text/html; charset=utf-8");

  4. UI第十七节——UIScrollView

    // 实例化一个ScrollView    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen main ...

  5. HDU 2296 Ring -----------AC自动机,其实我想说的是怎么快速打印字典序最小的路径

    大冥神的代码,以后能贴的机会估计就更少了....所以本着有就贴的好习惯,= =....直接贴 #include <bits/stdc++.h> using LL = long long ; ...

  6. Thinkphp 3.2.2 验证码check_verify方法,只能验证一次

    问题: Thinkphp 3.2.2 验证码check_verify方法,只能验证一次. function check_verify($code, $id = ''){ $verify = \Thin ...

  7. 使用ROW_NUMBER()+临时表+While 实现表遍历

    declare @table table(dlid int,RowNum int)insert into @table select dlid,ROW_NUMBER() over(order by d ...

  8. 那些PHP中没有全称的简写

    PHP中的GD库,全网没发现GD二字母的全称是什么,包括PHP.net,都搜不到GD.G应该是graphi,D是什么? die: 从php_mysql.dll到php_mysqli的变化,那个i是什么 ...

  9. 使用 bash 创建定时任务

    假设要增加每分钟执行一次的检测任务 (crontab -l; echo "* * * * * python check.py") | crontab 在 centos 6 上, 注 ...

  10. Ansible Ubuntu 安装部署

    一.安装: $ sudo apt-get install ansible 二.配置: a.基本配置 $ cd /etc/ansible/ $ sudo cp hosts hosts_back 备份一个 ...