(精华)2020年9月19日 ASP.NET Core 认证授权详解
发布日期:2021-06-29 15:12:27
浏览次数:3
分类:技术文章
本文共 18419 字,大约阅读时间需要 61 分钟。
Session的使用
public static class Sample01 { public static void Start() { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .ConfigureServices(collection => collection .AddDistributedMemoryCache() .AddSession()) .Configure(app => app .UseSession() .Run(ProcessAsync))) .Build() .Run(); static async Task ProcessAsync(HttpContext context) { var session = context.Session; await session.LoadAsync(); string sessionStartTime; if (session.TryGetValue("SessionStartTime", out var value)) { sessionStartTime = Encoding.UTF8.GetString(value); } else { sessionStartTime = DateTime.Now.ToString(CultureInfo.InvariantCulture); session.SetString("SessionStartTime", sessionStartTime); } context.Response.ContentType = "text/html"; await context.Response.WriteAsync($"
- Session ID:{session.Id} "); await context.Response.WriteAsync($"
- Session Start Time:{sessionStartTime} "); await context.Response.WriteAsync($"
- Current Time:{DateTime.Now}
public static class Sample02 { public static void Start() { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .ConfigureServices(collection => collection .AddDistributedMemoryCache() .AddSession()) .Configure(app => app .UseSession() .Run(ProcessAsync))) .Build() .Run(); static async Task ProcessAsync(HttpContext context) { var session = context.Session; await session.LoadAsync(); string sessionStartTime; if (session.TryGetValue("SessionStartTime", out var value)) { sessionStartTime = Encoding.UTF8.GetString(value); } else { sessionStartTime = DateTime.Now.ToString(CultureInfo.InvariantCulture); session.SetString("SessionStartTime", sessionStartTime); } // 使用反射获取Session Key var field = typeof(DistributedSession).GetTypeInfo().GetField("_sessionKey", BindingFlags.Instance | BindingFlags.NonPublic); var sessionKey = field?.GetValue(session); context.Response.ContentType = "text/html"; await context.Response.WriteAsync($"
- Session ID:{session.Id} "); await context.Response.WriteAsync($"
- Session Key:{sessionKey} "); await context.Response.WriteAsync($"
- Session Start Time:{sessionStartTime} "); await context.Response.WriteAsync($"
- Current Time:{DateTime.Now}
Cookie的使用
class Program { private static readonly DictionaryAccounts = new Dictionary { { "Admin", "123"}, { "UserA", "123"}, { "UserB", "123"} }; public static void Main(string[] args) { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .ConfigureServices(collection => collection .AddRouting() .AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie()) .Configure(app => app .UseAuthentication() .UseRouting() .UseEndpoints(endpoints => { endpoints.Map("/", RenderHomePageAsync); endpoints.Map("Account/Login", SignInAsync); endpoints.Map("Account/Logout", SignOutAsync); }))) .Build() .Run(); } public static async Task RenderHomePageAsync(HttpContext context) { if (context?.User?.Identity?.IsAuthenticated == true) { await context.Response.WriteAsync( @" Index " + $"Welcome {context.User.Identity.Name}
" + @" Sign Out "); } else { await context.ChallengeAsync(); } } public static async Task SignInAsync(HttpContext context) { if (string.CompareOrdinal(context.Request.Method, "GET") == 0) { await RenderLoginPageAsync(context, null, null, null); } else { var userName = context.Request.Form["username"]; var password = context.Request.Form["password"]; if (Accounts.TryGetValue(userName, out var pwd) && pwd == password) { var identity = new GenericIdentity(userName, "Passord"); var principal = new ClaimsPrincipal(identity); await context.SignInAsync(principal); } else { await RenderLoginPageAsync(context, userName, password, "Invalid user name or password!"); } } } private static Task RenderLoginPageAsync(HttpContext context, string userName, string password, string errorMessage) { context.Response.ContentType = "text/html"; return context.Response.WriteAsync( @"Login " + $"{errorMessage}
" + @" "); } public static async Task SignOutAsync(HttpContext context) { await context.SignOutAsync(); context.Response.Redirect("/"); } }
class Program { static void Main(string[] args) { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .ConfigureServices(collection => collection .AddDbContext(options => options .UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=AuthorizationDemo;Trusted_Connection=True;MultipleActiveResultSets=true") ) .AddRouting() .AddAuthorization() .AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme).AddCookie()) .Configure(app => app .UseAuthentication() .UseRouting() .UseEndpoints(endpoints => { endpoints.Map("/", RenderHomePageAsync); endpoints.Map("Account/Login", SignInAsync); endpoints.Map("Account/Logout", SignOutAsync); endpoints.Map("Account/AccessDenied", DenyAccessAsync); }))) .Build() .Run(); } public static async Task RenderHomePageAsync(HttpContext context) { if (context?.User?.Identity?.IsAuthenticated == true) { var requirement = new RolesAuthorizationRequirement(new [] { "ADMIN" }); var authorizationService = context.RequestServices.GetRequiredService (); var result = await authorizationService.AuthorizeAsync(context.User, null, new IAuthorizationRequirement[] { requirement }); if (result.Succeeded) { await context.Response.WriteAsync( @" Index " + $"{context.User.Identity.Name}, you are authorized.
" + @" Sign Out "); } else { await context.ForbidAsync(); } } else { await context.ChallengeAsync(); } } public static async Task SignInAsync(HttpContext context) { if (string.Compare(context.Request.Method, "GET") == 0) { await RenderLoginPageAsync(context, null, null, null); } else { string userName = context.Request.Form["username"]; string password = context.Request.Form["password"]; var dbContext = context.RequestServices.GetRequiredService(); var user = await dbContext.Users.Include(it => it.Roles).SingleOrDefaultAsync(it => it.UserName == userName.ToUpper()); if (user?.Password == password) { var identity = new GenericIdentity(userName, CookieAuthenticationDefaults.AuthenticationScheme); foreach (var role in user.Roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role.NormalizedRoleName)); } var principal = new ClaimsPrincipal(identity); await context.SignInAsync(principal); } else { await RenderLoginPageAsync(context, userName, password, "Invalid user name or password!"); } } } private static Task RenderLoginPageAsync(HttpContext context, string userName, string password, string errorMessage) { context.Response.ContentType = "text/html"; return context.Response.WriteAsync( @" Login " + $"{errorMessage}
" + @" "); } public static async Task SignOutAsync(HttpContext context) { await context.SignOutAsync(); await context.ChallengeAsync(new AuthenticationProperties { RedirectUri = "/" }); } public static Task DenyAccessAsync(HttpContext context) { return context.Response.WriteAsync( @"Index " + $"{context.User.Identity.Name}, your access is denied.
" + @" Sign Out "); } }
CookieAuthentication
class Program { static void Main(string[] args) { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .ConfigureServices(collection => collection .AddDbContext(options => options .UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=AuthorizationDemo;Trusted_Connection=True;MultipleActiveResultSets=true") ) .AddRouting() .AddAuthorization(options => { var requirement = new RolesAuthorizationRequirement(new [] { "ADMIN" }); var policy = new AuthorizationPolicy(new IAuthorizationRequirement[] { requirement }, new string[0]); options.AddPolicy("HomePage", policy); }) .AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme).AddCookie()) .Configure(app => app .UseAuthentication() .UseRouting() .UseEndpoints(endpoints => { endpoints.Map("/", RenderHomePageAsync); endpoints.Map("Account/Login", SignInAsync); endpoints.Map("Account/Logout", SignOutAsync); endpoints.Map("Account/AccessDenied", DenyAccessAsync); }))) .Build() .Run(); } public static async Task RenderHomePageAsync(HttpContext context) { if (context?.User?.Identity?.IsAuthenticated == true) { var authorizationService = context.RequestServices.GetRequiredService (); var result = await authorizationService.AuthorizeAsync(context.User, "HomePage"); if (result.Succeeded) { await context.Response.WriteAsync( @" Index " + $"{context.User.Identity.Name}, you are authorized.
" + @" Sign Out "); } else { await context.ForbidAsync(); } } else { await context.ChallengeAsync(); } } public static async Task SignInAsync(HttpContext context) { if (string.Compare(context.Request.Method, "GET") == 0) { await RenderLoginPageAsync(context, null, null, null); } else { string userName = context.Request.Form["username"]; string password = context.Request.Form["password"]; var dbContext = context.RequestServices.GetRequiredService(); var user = await dbContext.Users.Include(it => it.Roles).SingleOrDefaultAsync(it => it.UserName == userName.ToUpper()); if (user?.Password == password) { var identity = new GenericIdentity(userName, CookieAuthenticationDefaults.AuthenticationScheme); foreach (var role in user.Roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role.NormalizedRoleName)); } var principal = new ClaimsPrincipal(identity); await context.SignInAsync(principal); } else { await RenderLoginPageAsync(context, userName, password, "Invalid user name or password!"); } } } private static Task RenderLoginPageAsync(HttpContext context, string userName, string password, string errorMessage) { context.Response.ContentType = "text/html"; return context.Response.WriteAsync( @" Login " + $"{errorMessage}
" + @" "); } public static async Task SignOutAsync(HttpContext context) { await context.SignOutAsync(); await context.ChallengeAsync(new AuthenticationProperties { RedirectUri = "/" }); } public static Task DenyAccessAsync(HttpContext context) { return context.Response.WriteAsync( @"Index " + $"{context.User.Identity.Name}, your access is denied.
" + @" Sign Out "); } }
权限认证交互示例
public class Program { public static void Main() { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .UseUrls("http://*:443") .Configure(app => app.Run(ProcessAsync))) .Build() .Run(); static async Task ProcessAsync(HttpContext httpContext) { httpContext.Response.ContentType = "text/html"; var html = @"
public class Program { public static void Main() { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .UseUrls("http://*:8080") .Configure(app => app .UsePathBase("/contacts") .Run(ProcessAsync))) .Build() .Run(); static Task ProcessAsync(HttpContext httpContext) { var response = httpContext.Response; response.ContentType = "application/json"; var contacts = new Contact[] { new Contact("张三", "123", "zhangsan@qq.com"), new Contact("李四","456", "lisi@qq.com"), new Contact("王五", "789", "wangwu@qq.com") }; return response.WriteAsync(JsonConvert.SerializeObject(contacts)); } } }
转载地址:https://codeboy.blog.csdn.net/article/details/108524602 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月05日 02时56分36秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
芯片IC附近为啥要放0.1uF的电容?
2019-04-29
电赛 | 19年全国一等奖,北航学子回忆录。
2019-04-29
电赛 | 19年全国一等奖,北航学子回忆录(上)
2019-04-29
电赛 | 19年全国一等奖,北航学子回忆录(下)
2019-04-29
突破!台积电1nm芯片,有了新进展。
2019-04-29
一文读懂全系列树莓派!
2019-04-29
自制一个害羞的口罩,见人就闭嘴,戴着可以喝奶茶
2019-04-29
聊聊我是如何编程入门的
2019-04-29
J-Link该如何升级固件?
2019-04-29
485通信自动收发电路,历史上最详细的解释
2019-04-29
【视觉盛宴三】不好意思,这些线材接口的横截面真的没见过
2019-04-29
一位头发发白的神人教你怎么写程序,运维,买电脑,写文章,平面设计!
2019-04-29
【第二期】那些设计漂亮、有创意的电路板!
2019-04-29
【第三期】那些设计漂亮、有创意的电路板!
2019-04-29
继续推荐公众号~
2019-04-29
「第二篇」全国一等奖,经验帖。
2019-04-29
「第三篇」全国电子设计竞赛,这些你必须知道的比赛细节,文末附上近十年电赛题目下载...
2019-04-29
5G小科普(漫画版,So easy!)
2019-04-29
无人再提华强北
2019-04-29
千万不要小瞧那些不好好写代码的程序员
2019-04-29