关于 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下的自定义程序页面,现在我们需要给自定义页面做一下权限认证.要求 ...
随机推荐
- error MSB8020 问题解决
产生原因: 1.vs 版本过低 2.项目平台工具选择不正确 解决方案: 1.安装VS2015以上的版本 2.选择项目属性,修改平台工具,选择当前版本可用的工具. 具体步骤:右键点击你的项目,选择 Pr ...
- eclipse创建spring boot项目,tomcat启动成功,但http://localhost:8080无法访问报错404解决方案
spring boot的启动程序启动后,在访问http://localhost:8080地址的时候出现了错误,为什么出错网上我找了好久也没有得出具体的解决办法 当我指定到具体的action的时候,却可 ...
- Java演算法-「馬踏棋盤問題」
/* * 馬踏棋盤問題:(貪婪法求解) * 棋盤有64個位置,“日”字走法,剛好走滿整個棋盤 */ //下一個走法的方向類 class Direction{ int x; int y; int way ...
- python pip 安装模块步骤
在线安装,cmd输入 命令:pip install mysql-connector-python 注:直接在默认路径下输入
- AppStore关键词覆盖法则标记
https://www.jianshu.com/p/6b39b0dc6ba4 多批设置关键字
- angularjs知识点
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- MarkDown语言
参考: 参考:https://typora.io/ 参考:https://caret.io/ Markdown是一种轻量级标记语言,创始人为約翰·格魯伯(英语:John Gruber). 它允许人们“ ...
- composer相关使用
#composer安装 curl -sS https://getcomposer.org/installer | php #如果该命令执行不了,通过其他方式下载install文件后再执行“php in ...
- 【Python全栈-HTML】HTML引入文件的绝对路径、相对路径、根目录
HTML引入文件的绝对路径.相对路径.根目录 什么是绝对路径?绝对路径指的是文件的真正路径,使用绝对路径链接外部资源,如:图片.超级链接.flash.音频.视频等等.代码如下: 1.引入网络上的资源: ...
- mysql-5.7 通过apt或者yum安装方式
此文章仅记录使用apt-get安装mysql. 通过以下命令安装MySQL: shell> sudo apt-get install mysql-server 这将安装MySQL服务器的包,以及 ...