当前位置:网站首页>. 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
边栏推荐
猜你喜欢
win32
基于邻接矩阵的广度优先遍历
FPGA实现图像二值形态学滤波——腐蚀膨胀
Prompt to update to the latest debug version during vscode debugging
One minute to understand the difference between synchronous, asynchronous, blocking and non blocking
vscode调试时提示更新到最新调试版本
Markov decision process (MDP): gambler problem
regular expression
深度好文:什么是超网 Supernetting?
Chrome browser developer tool usage
随机推荐
图的深度优先遍历
One year's work
初识Opengl
The first intimate contact of caching technology
jenkins汉化及汉化无效解决方案
Getting to know OpenGL
Implementation of depth first traversal based on adjacency matrix
How to set an achievable annual goal?
其他代码,,vt,,,k
Disruptor (I) sequence
Snake game
【无标题】vsbiji esp....32
Depth first traversal based on adjacency table
Prometeus 2.33.0 新特性
cv==biaoding---open----cv001
Keda 2.7.1 brief analysis of scaledjob code
Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined) C. Felicity is Coming!
Connecting the projector
ARM流水线如何提高代码执行效率
High performance and high availability computing architecture based on microblog comments