当前位置:网站首页>. Net7 miniapi (special part):preview5 optimizes JWT verification (Part 2)
. Net7 miniapi (special part):preview5 optimizes JWT verification (Part 2)
2022-06-26 02:19:00 【Dotnet cross platform】
Preview5 There is no change in the way the policy is validated , Just built in Token Generation , and 《.NET6 And MiniAPI( Ten ): Authentication and authorization policy based 》 The verification method is basically the same , The validation parameters used for generation and validation should be consistent , By inheritance AuthorizationHandler For each request .
On the specific route , use RequireAuthorization("Permission") To configure the policy name , In order to achieve the requested steering verification .
Not much said , Look at the code implementation , Sure 《.NET6 And MiniAPI( Ten ): Authentication and authorization policy based 》 For comparison .
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
#region Add policy validation parameters
builder.Authentication.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890abcdefg")),
ValidateIssuer = true,
ValidIssuer = "http://localhost:5274",
ValidateAudience = true,
ValidAudience = "http://localhost:5274",
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
}; ;
});
// Add policy name and note and policy validation service
builder.Services
.AddAuthorization(options =>
{
// Add policy name
options.AddPolicy("Permission", policyBuilder => policyBuilder.AddRequirements(new PermissionRequirement()));
})
.AddSingleton(new List<Permission> { new Permission { RoleName = "admin", Url = "/Policy", Method = "get" } })
.AddSingleton<IAuthorizationHandler, PermissionHandler>();
var app = builder.Build();
// Sign in , Generate token
app.MapGet("/login", () =>
{
// use JWTSecurityTokenHandler Generate token
return new JwtSecurityTokenHandler().WriteToken(
new JwtSecurityToken(
issuer: "http://localhost:5274",
audience: "http://localhost:5274",
claims: new Claim[] {
new Claim(ClaimTypes.Role, "admin"),
new Claim(ClaimTypes.Name, " Gui Suwei ")
},
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddSeconds(500000),
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890abcdefg")),
SecurityAlgorithms.HmacSha256)
)
);
});
app.MapGet("/policy", (ClaimsPrincipal user) => $"Hello user :{user.Identity?.Name}, role :{user.Claims?.Where(s => s.Type == ClaimTypes.Role).First().Value}. This is a policy!").RequireAuthorization("Permission");
app.Run();
#region Policy validation function
public class PermissionRequirement : IAuthorizationRequirement
{
}
// A collection of entities with permissions
public class Permission
{
public string? RoleName { get; set; }
public string? Url { get; set; }
public string? Method { get; set; }
}
// Permission verification class
public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
{
private readonly List<Permission> _userPermissions;
public PermissionHandler(List<Permission> permissions)
{
_userPermissions = permissions;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
if (context.Resource is DefaultHttpContext)
{
var httpContext = context.Resource as DefaultHttpContext;
var questPath = httpContext?.Request?.Path;
var method = httpContext?.Request?.Method;
var isAuthenticated = context?.User?.Identity?.IsAuthenticated;
if (isAuthenticated.HasValue && isAuthenticated.Value)
{
var role = context?.User?.Claims?.SingleOrDefault(s => s.Type == ClaimTypes.Role)?.Value;
if (_userPermissions.Where(w => w.RoleName == role && w.Method?.ToUpper() == method?.ToUpper() && w.Url?.ToLower() == questPath).Count() > 0)
{
context?.Succeed(requirement);
}
else
{
context?.Fail();
}
}
}
return Task.CompletedTask;
}
}
#endregion边栏推荐
猜你喜欢

【图像过滤】基于matlab GUI图像过滤系统【含Matlab源码 1913期】

Visual studio 2013 redistributable is installed, but MySQL installation fails

MySQL必须掌握4种语言!

图的广度优先遍历

Prompt to update to the latest debug version during vscode debugging

Shell learning record (II)

Agent challenge - "Olympic running"

SDRAM控制器——添加读写FIFO

Cross server SQL connection configuration

vscode调试时提示更新到最新调试版本
随机推荐
Sqlyog shortcut keys
Simplex method (1)
基于邻接表的深度优先遍历
Interface test case design
树莓派 + AWS IoT 入门实验
Record a weird picture upload problem
Output Lua print to the cocos2d console output window
How to set an achievable annual goal?
PyQt theme
win32
基于邻接矩阵的深度优先遍历实现
Prompt to update to the latest debug version during vscode debugging
图的广度优先遍历
基於鄰接矩陣的廣度優先遍曆
Scala Basics (II): variables and data types
Raspberry pie + AWS IOT introductory experiment
SDRAM controller -- implementation of arbitration module
螺旋矩阵
weishi相机显示
ARM流水线如何提高代码执行效率