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. ORACLE11g 重装系统后根据dbf恢复数据库

    1.安装一个和原系统一致的oracle 环境,主要包括版本.数据名sid.实例名.路径和数据库编码一致 2.修改listener.ora的参数 SID_LIST_LISTENER = (SID_LIS ...

  2. python selenium ——— 动态id、class定位

    什么样的是动态id呢? 动态id就是第一次点击显示的id与二次点击显示的不一样,一般是元素属性中包含一段数字的这种情况. 类似这种: 1 <input type="button&quo ...

  3. Nginx基本安装

    Windows安装Nginx 解压:nginx-windows 双击: nginx.exe 能看到nginx欢迎界面说明,nginx安装成功 演示下 nginx做静态服务器 启动Nginx C:\se ...

  4. Hibernate用注解方式实现一对多、多对多关系

    一.一对多关系 1.在上一篇日志中用.xml配置文件项目基础上,再往lib目录先添加一个包-hibernate-jpa-2.0-api-1.0.0.Final.jar 2.新建一个com.st.bea ...

  5. 课堂笔记及知识点----栈和队列(2018/10/24(am))

    栈: Stack<int>  xt=new Stack<int>() ; 先进后出,后进先出,水杯结构,顺序表类似 常用方法:   .pop---->出栈,弹栈     ...

  6. Differenciate or distinguish between outlook attachment and embedded image/signature using property accessor in C#.NET

    These days, outlook emails are composed in three formats; plain text, html and rtf (rich text format ...

  7. JDK安装路径下的JRE与独立安装的JRE区别

    在JDK安装目录下的子文件下,已经默认安装了一个jre.且与独立安装的JRE6所包含的文件几乎完全一样. JDK里面内置的JRE和独立的JRE是有一点差别的: 在JDK安装文件中包含了一个完整的独立版 ...

  8. 提取一个txt 文档中含指定字符串的所有行

    将一个txt 文档中含指定字符串内容的所有行提取出来并保存至新的txt文档中 例如,要提取 1.txt 中所有包含”aaa” 的行的内容 只需在此文件夹中新建一个bat文件,输入以下代码,双击运行,便 ...

  9. rapidjson对于json的序列化与反序列化

    转载: https://blog.csdn.net/qq849635649/article/details/52678822 #include "rapidjson/stringbuffer ...

  10. JS中使用base64编码上传下载文件

    下载文件:使用FileSaver.js   https://github.com/eligrey/FileSaver.js/blob/master/README.md 手机端UC浏览器无法下载  安卓 ...