关于 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下的自定义程序页面,现在我们需要给自定义页面做一下权限认证.要求 ...
随机推荐
- MySQL性能分析及explain的使用(转)
1.使用explain语句去查看分析结果,如 explain select * from test1 where id=1; 会出现: id selecttype table type possibl ...
- JBPM工作流(八)——流程实例(PI)Process Instance
/** * 流程实例 * * 启动流程实例 * * 完成任务 * * 查询 * * 查询流程实例 * * 查询任务 * * 查询正在 ...
- viewport的故事(二)
挑重点的翻译 自原文 https://www.quirksmode.org/mobile/viewports2.html 在这一页我们将聊一聊移动端的浏览器. 移动端的问题 最明显的问题 ...
- Windows系统Git安装配置
Git的安装 Git是一个开源的分布式的版本控制软件,是Linus Torvalds 为了方便开源贡献者协同开发和管理 Linux 内核开发替代BitKe而开发的. 打开git官网的下载地址:http ...
- CISCO MDS – Useful ‘Show’ Commands
CISCO MDS – Useful ‘Show’ Commands CONFIG:show startup-configshow running-configshow running-config ...
- Design Principle, Design Patterns And Refactoring
https://refactoring.guru/smells/feature-envy https://stackoverflow.com/questions/1242994/effective-c ...
- DjangoRestFramework学习二之序列化组件、视图组件 serializer modelserializer
DjangoRestFramework学习二之序列化组件.视图组件 本节目录 一 序列化组件 二 视图组件 三 xxx 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 序列化组 ...
- 长时间关机测试脚本.VBS
Sub Main Dim cnt Dim delay Dim time Dim atttime atttime = 20 delay = 3000 time = 50 cnt_time=3 crt.s ...
- C++11 新特性之operator "" xxx
从C++11开始,我们可以使用以下形式通过常量字符串构造自定义类型, 比如: class Person { public: Person(const std::string& name): _ ...
- python写算法中的栈
########### 栈的使用 ############### class StackFullError(Exception): pass class StackEmptyError(Excepti ...