1、自定义权限需要扩展 Microsoft.AspNetCore.Authentication 实现一套接口

IAuthenticationHandler, IAuthenticationSignInHandler, IAuthenticationSignOutHandler

   public class MyAuthenticationHandler : IAuthenticationHandler, IAuthenticationSignInHandler, IAuthenticationSignOutHandler
{
public AuthenticationScheme Scheme { get; private set; }
protected HttpContext Context { get; private set; } public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
Scheme = scheme;
Context = context;
return Task.CompletedTask;
} public Task ChallengeAsync(AuthenticationProperties properties)
{
Context.Response.Redirect("/Account/login");
return Task.CompletedTask;
} public async Task<AuthenticateResult> AuthenticateAsync()
{
var result = await Task.Run<AuthenticateResult>(() =>
{
var cookie = Context.Request.Cookies["myCookie"];
if (string.IsNullOrEmpty(cookie))
{
return AuthenticateResult.NoResult();
}
return AuthenticateResult.Success(this.Deserialize(cookie));
}); return result;
} public Task ForbidAsync(AuthenticationProperties properties)
{
Context.Response.StatusCode = ;
return Task.CompletedTask;
} public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
var ticket = new AuthenticationTicket(user, properties, Scheme.Name);
Context.Response.Cookies.Append("myCookie", Serialize(ticket));
return Task.CompletedTask;
} public Task SignOutAsync(AuthenticationProperties properties)
{
Context.Response.Cookies.Delete("myCookie");
return Task.CompletedTask;
} private string Serialize(AuthenticationTicket ticket)
{
byte[] byteTicket = TicketSerializer.Default.Serialize(ticket);
return System.Text.Encoding.Default.GetString(byteTicket);
} private AuthenticationTicket Deserialize(string ticket)
{
byte[] byteTicket = System.Text.Encoding.Default.GetBytes(ticket);
return TicketSerializer.Default.Deserialize(byteTicket);
}
}

2、在 ConfigureServices 中注册服务

        // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(
option =>
{
option.DefaultScheme = "myScheme";
option.AddScheme<MyAuthenticationHandler>("myScheme", "demo scheme");
}); services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); services.AddSession(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

3、在 void Configure(IApplicationBuilder app, IHostingEnvironment env) 中使用权限检查

app.UseAuthentication();

4、在 Controller 中实现自己的 Login 、Logout

       [AllowAnonymous]
public async void Login(string username, string password)
{
var claimIdentity = new ClaimsIdentity("CustomApiKeyAuth");
claimIdentity.AddClaim(new Claim(ClaimTypes.Name, username));
claimIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
await HttpContext.SignInAsync("myScheme", new ClaimsPrincipal(claimIdentity));
await HttpContext.Response.WriteAsync($"Hello {username} login!");
} public async void Logout()
{
await HttpContext.SignOutAsync("myScheme");
}

5、在 Controller 中使用权限检查特性

       [Authorize(Roles = "Admin")]
public void Test()
{
var user = HttpContext.User;
HttpContext.Response.WriteAsync($"Test {user.Identity.Name}!");
}

6、测试

在浏览器上输入 https://localhost:44318/account/login?username="aaa"

系统输出: Hello "aaa" login!

在浏览器上输入 https://localhost:44318/account/test

系统输出 : Test "aaa"!

成功运行了。

7、结束语

虽然只是简单的框架代码,但实现了完整的流程控制。方便初学者。

需要源代码的朋友点这里下载

8、参考资料

ASP.NET Core 2.0 authentication middleware

关于 DotNetCore 的自定义权限管理的更多相关文章

  1. DRF内置权限组件之自定义权限管理类

    DRF内置权限组件permissions 权限控制可以限制用户对于视图的访问和对于具体数据对象的访问. 在执行视图的dispatch()方法前,会先进行视图访问权限的判断 在通过get_object( ...

  2. thinkphp自定义权限管理之名称判断

    权限管理,就是给不同的用户分配不同的权限.当用户登录或者操作时候进行判断,来阻止用户进行权限以外的操作.本次讲的是当用户登录一刻,只显示权限开启的内容. 一.建立数据库. 1.权限表funcla.来存 ...

  3. android 自定义权限管理

    在Android6.0后有些权限就需要进行询问,虽然可以将targetSdkVersion设置成小于等于23,但是这样可能有些东西无法使用,所以要进行权限的管理. 实现逻辑:打开页面就询问权限,如果没 ...

  4. C#_MVC 自定义AuthorizeAttribute实现权限管理

    随笔- 28  文章- 31  评论- 16 MVC 自定义AuthorizeAttribute实现权限管理   在上一节中提到可以使用AuthorizeAttribute进行权限管理: [Autho ...

  5. MVC 自定义AuthorizeAttribute实现权限管理

    在上一节中提到可以使用AuthorizeAttribute进行权限管理: [Authorize] public ActionResult TestAuthorize() { return View() ...

  6. 权限管理(java+struts2(自定义标签)实现)--------->全代码演示

    地址:http://blog.chinaunix.net/uid-24343152-id-3673026.html 最近由于项目不是很紧所以总结了之前做了n遍的权限管理功能.以便之后系统copy之用. ...

  7. MVC自定义AuthorizeAttribute实现权限管理

    [转]MVC自定义AuthorizeAttribute实现权限管理 原文载自:小飞的DD http://www.cnblogs.com/feiDD/articles/2844447.html 网站的权 ...

  8. 潭州课堂25班:Ph201805201 django框架 第十三课 自定义404页面,auth系统中的User模型,auth系统权限管理 (课堂笔记)

    当 DEBUG=True 时,django 内部的404报错信息, 自带的报错信息, 要自定义404信息,要先把 DEBUG=False , 之后要自定义4040页面,有两种方法, 方法1,在创建40 ...

  9. SharePoint _layouts下自定义程序页面权限管理

    在sharepoint中,_layouts下的自定义页面没有特别的权限,只要用户能访问sharepoint站点就可以访问_layouts下的自定义程序页面,现在我们需要给自定义页面做一下权限认证.要求 ...

随机推荐

  1. jquery第一篇

    1  jquery是什么 <1> jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team. <2>jQuery是继 ...

  2. angular.identity()

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  3. Mybatis_3.基于注解的增删改查

    1.实体类User.java public class User { private int id; private String name; private int age; //getter.se ...

  4. ECMA Script 6_symbol(symbol.iterator) 新接口_iterator接口

    iterator 接口 只要部署了 iterator 接口 symbol(symbol.iterator), 则可以进行 for...of  遍历

  5. [LeetCode] Number of Subarrays with Bounded Maximum 有界限最大值的子数组数量

    We are given an array A of positive integers, and two positive integers L and R (L <= R). Return ...

  6. checkPathValidity 检查所有agent的corridor的m_path是否有效

    在checkPathValidity(检查所有agent的corridor的m_path是否有效) 如果是无效的要进行重新设置并且设置replan 首先获得第一个polygon,m_path[0] 这 ...

  7. 1. Scala概述

    1.1 概述 联邦理工学院洛桑(EPFL)的Martin Odersky于2001年开始设计Scala Scala是Scalable Language的简写,是一门多范式的编程语言 1.2 Scala ...

  8. python基础2 数据类型、数据拼接、数据转换

    一.数据类型 1.字符串 字符串英文string,简写str,只要是被[单/双/三引号]这层皮括起来的内容,不论那个内容是中文.英文.数字甚至火星文.只要是被括起来的,就表示是字符串类型 如:prin ...

  9. su: authentication failure 解决方法

    在Linux上切换root时,密码正确..但提示:su: authentication failure ->sudo passwd ->Password:你当前的密码 ->Enter ...

  10. 接口测试工具-Jmeter使用笔记(八:模拟OAuth2.0协议简化模式的请求)

    背景 博主的主要工作是测试API,目前已经用Jmeter+Jenkins实现了项目中的接口自动化测试流程.但是马上要接手的项目,API应用的是OAuth2.0协议授权,并且采用的是简化模式(impli ...