利用 cookie 模式 》》 框架默认的
利用 cookie 模式 》》 策略授权
》》》策略对应的处理逻辑,这里可以请求action时,如果添加了策略,则会触发对应的策略处理模块
using Microsoft.AspNetCore.Authorization;namespace ZenAuth.Coms
{public class CustomAuthorizationHandler : AuthorizationHandler<CustomRequirement>{private readonly IStudent _studentService;//可以实现注入public CustomAuthorizationHandler(IStudent studentService){_studentService = studentService;}protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRequirement requirement){// 使用 _customService 进行处理this._studentService.Write();Console.WriteLine(""); if (1 == 1){// 验证成功context.Succeed(requirement);}return Task.CompletedTask;}}
}
》》》添加策略对应的 参数
using Microsoft.AspNetCore.Authorization;namespace ZenAuth.Coms
{public class CustomRequirement: IAuthorizationRequirement{// 可以在这里定义需要的任何属性或方法public CustomRequirement(){}}
}
》》》
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.BearerToken;
using ZenAuth.Coms;
using Microsoft.AspNetCore.Authorization;namespace ZenAuth
{public class Program{public static void Main(string[] args){var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllersWithViews();builder.Services.AddSingleton<IAuthorizationHandler, CustomAuthorizationHandler>();builder.Services.AddSingleton<IStudent, Student>();#region 认证builder.Services.AddAuthentication(options =>{options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;}).AddCookie(options =>{//登陆地址options.LoginPath = "/Account/Index";//禁止访问地址options.AccessDeniedPath = "/Account/Index";//Cookie过期时间options.ExpireTimeSpan = TimeSpan.FromMinutes(20);//校验过期});#endregion#region 授权// 默认的模式//builder.Services.AddAuthorization();//授权策略模式 扩展 builder.Services.AddAuthorization(options =>{options.AddPolicy("CustomPolicy", policy =>{policy.Requirements.Add(new CustomRequirement());});});#endregionvar app = builder.Build();// Configure the HTTP request pipeline.if (!app.Environment.IsDevelopment()){app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles();app.UseRouting();#region 认证和授权中间件//app.UseAuthentication();app.UseAuthorization();#endregionapp.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");app.Run();}}
}
源码