关于 DotNetCore 的自定义权限管理
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 的自定义权限管理的更多相关文章
- DRF内置权限组件之自定义权限管理类
DRF内置权限组件permissions 权限控制可以限制用户对于视图的访问和对于具体数据对象的访问. 在执行视图的dispatch()方法前,会先进行视图访问权限的判断 在通过get_object( ...
- thinkphp自定义权限管理之名称判断
权限管理,就是给不同的用户分配不同的权限.当用户登录或者操作时候进行判断,来阻止用户进行权限以外的操作.本次讲的是当用户登录一刻,只显示权限开启的内容. 一.建立数据库. 1.权限表funcla.来存 ...
- android 自定义权限管理
在Android6.0后有些权限就需要进行询问,虽然可以将targetSdkVersion设置成小于等于23,但是这样可能有些东西无法使用,所以要进行权限的管理. 实现逻辑:打开页面就询问权限,如果没 ...
- C#_MVC 自定义AuthorizeAttribute实现权限管理
随笔- 28 文章- 31 评论- 16 MVC 自定义AuthorizeAttribute实现权限管理 在上一节中提到可以使用AuthorizeAttribute进行权限管理: [Autho ...
- MVC 自定义AuthorizeAttribute实现权限管理
在上一节中提到可以使用AuthorizeAttribute进行权限管理: [Authorize] public ActionResult TestAuthorize() { return View() ...
- 权限管理(java+struts2(自定义标签)实现)--------->全代码演示
地址:http://blog.chinaunix.net/uid-24343152-id-3673026.html 最近由于项目不是很紧所以总结了之前做了n遍的权限管理功能.以便之后系统copy之用. ...
- MVC自定义AuthorizeAttribute实现权限管理
[转]MVC自定义AuthorizeAttribute实现权限管理 原文载自:小飞的DD http://www.cnblogs.com/feiDD/articles/2844447.html 网站的权 ...
- 潭州课堂25班:Ph201805201 django框架 第十三课 自定义404页面,auth系统中的User模型,auth系统权限管理 (课堂笔记)
当 DEBUG=True 时,django 内部的404报错信息, 自带的报错信息, 要自定义404信息,要先把 DEBUG=False , 之后要自定义4040页面,有两种方法, 方法1,在创建40 ...
- SharePoint _layouts下自定义程序页面权限管理
在sharepoint中,_layouts下的自定义页面没有特别的权限,只要用户能访问sharepoint站点就可以访问_layouts下的自定义程序页面,现在我们需要给自定义页面做一下权限认证.要求 ...
随机推荐
- php发送短信验证码
业务: 手机端点击发送验证码,请求发送到php端,由php调用榛子云短信http://smsow.zhenzikj.com的短信接口,生成验证码并发送. SDK下载: http://smsow.zhe ...
- javascript的数组之slice()
slice()方法创建一个新数组,将原数组的部分元素拷贝到新数组,并将新数组返回,且原数组不会被修改. var animals = ['ant', 'bison', 'camel', 'duck', ...
- 2019.4.10 初识puppeteer
注:原地址:https://www.cnblogs.com/paris-test/p/9705075.html 一.Puppeteer 介绍 Puppeteer 翻译是操纵木偶的人,利用这个工具,我们 ...
- ubuntu下安装和配置pycharm和pyqt5
参考网址:https://blog.csdn.net/qq_37541097/article/details/80021315 PyQt是Python语言的GUI编程解决方案之一.可以用来代替Pyth ...
- Python: map() and reduce()
map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回. 举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个lis ...
- worker pool Handling 1 Million Requests per Minute with Golang
小结: 1. 我们决定使用 Go 通道的一种常用模式构建一个两层的通道系统,一个通道用作任务队列,另一个来控制处理任务时的并发量. 这个办法是想以一种可持续的速率.并发地上传数据至 S3 存储,这样既 ...
- docker的安装和升级
1.删除docker sudo apt-get purge docker.io sudo rm -rf /etc/docker/ sudo apt-get autoremove 2. 安装docker ...
- 学习Makefile
1> 编译一个文件2> 编译多个文件3> 编译多个目录下的文件4> inclue makefile5> 使用规则1>target:depend[tab]cmddep ...
- maven插件--assembly
之前maven项目中使用assembly插件单独打包项目依赖包,项目只有一个模块也就一个pom,配置这个插件,一切很顺利.但是现在的项目复杂了,有parent有child,多模块.按照之前的做法怎么也 ...
- hystrix参数使用方法
hystrix+feign+ribbon,但是可能很多人都知道hystrix还有线程隔离,信号量隔离,等等各种参数配置,在这几就记录下hystrix的参数, 一.hystrix参数使用方法 通过注解@ ...