(精华)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 Dictionary
Accounts = 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 = @"
    "; await httpContext.Response.WriteAsync(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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

    上一篇:(精华)2020年9月18日 ASP.NET Core 异常页面详解
    下一篇:(精华)2020年9月20日 ASP.NET Core WebAPI数据协议OData的使用

    发表评论

    最新留言

    做的很好,不错不错
    [***.243.131.199]2024年04月05日 02时56分36秒