当前位置:网站首页>. 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边栏推荐
猜你喜欢

ARM流水线如何提高代码执行效率

Exploring temporary information for dynamic network embedding

OA process editing

SQL column value to row value (unpivot)

How do I fix the iPhone green screen problem? Try these solutions

图的深度优先遍历

Scala Basics (II): variables and data types
![[JS] free API to judge holidays, working days, Saturdays and Sundays](/img/e1/8b742082385bb5e60f74beb3b81c7d.png)
[JS] free API to judge holidays, working days, Saturdays and Sundays

jenkins汉化及汉化无效解决方案

Bloc入门之Cubit详解
随机推荐
Implementation of image binary morphological filtering based on FPGA -- Corrosion swelling
Prompt to update to the latest debug version during vscode debugging
How do I fix the iPhone green screen problem? Try these solutions
哪个证券公司手机股票开户更好更安全?
Magnifier case
如何使用命令将文件夹中的文件名(包括路径)写入到txt文件中
Interface test case design
基于邻接表的广度优先遍历
[untitled] vsbiji ESP thirty-two
Fastadmin applet assistant is purchased, but the work order cannot be published in the problem work order
Redis linked list
Redis6.0 new feature - ACL (permission control list) implements the restriction of user executable commands and keys
螺旋矩阵
OA process editing
Exploring temporary information for dynamic network embedding
图的深度优先遍历
FPGA实现图像二值形态学滤波——腐蚀膨胀
V4l2+qt video optimization strategy
【js】免费api判断节假日、工作日和周六日
shell学习记录(一)