本帖最后由 陌小北 于 2024-1-18 14:55 编辑
[C#] 纯文本查看 复制代码
using jwtAuthTest.AuthorizationExtend;
using jwtAuthTest.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
namespace jwtAuthTest
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;//不能少,默认的授权渠道
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/Login"; //如果在鉴权的过程中,没有解析到用户的信息,就跳转到登录页
options.AccessDeniedPath = "/AccessDeniedPath"; //解析到了用户信息,但是根据当前的用户信息判断的时候,不允许支持访问资源
});
//配置添加授权规则
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminPolicy", policyBuilder =>
{
policyBuilder.RequireAssertion(context =>
{
if (context.User.Claims == null || context.User.Claims.Count() <= 0)
{
return false;
}
return true;
});
policyBuilder.AddRequirements(new AdminCookieRequirement(CookieAuthenticationDefaults.AuthenticationScheme));
});
});
builder.Services.AddSingleton<IAuthorizationHandler, AdminCookieHandler>();
builder.Services.AddSingleton<IUserService, UserService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
|