当前位置:网站首页>. net core JWT dynamic configuration interface and permissions

. net core JWT dynamic configuration interface and permissions

2020-12-06 01:33:00 itread01

Through the last article .Net Core Official JWT Authorization verification has learned JWT Authorization of . You can find a problem , That is, if the characters that can be used by each interface are written dead , It will be very troublesome if there is any modification , Although with policy It can alleviate to a certain extent , But there is still no cure .

therefore , You need to set up interfaces and permissions dynamically , It's up to us to handle it ourselves .

Let's create a class first  PermissionRequirement Inheritance interface  IAuthorizationRequirement, This class is an interface role relationship class , The fields inside can be added according to your own needs .

public class PermissionRequirement : IAuthorizationRequirement
{
  public string Url { get; set; }
  public List<string> Roles { get; set; }
}

Then create a processing class PermissionHandler Inherit  AuthorizationHandler Class , To handle the relationship between request mediation and role permission .

public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
{
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
    {
        // Simulate access from a database or cache url License information for 
        var roles = new List<PermissionRequirement>();
        roles.Add(new PermissionRequirement() { Url = "weatherforecast", Roles = new List<string>() { "system" } });
        //JWT Of token Information such as announcements in will be automatically parsed in context in 
        var resource = ((Microsoft.AspNetCore.Routing.RouteEndpoint)context.Resource).RoutePattern;
        foreach(var t in context.User.Identities)
        {
            foreach(var claim in t.Claims)
            {
                // Through Type You can determine the type of declaration , Deal with role To get the character information 
                if(claim.Type == ClaimTypes.Role)
                {
                    if(roles.Exists(x => x.Roles.Exists(role => role == claim.Value) && x.Url == resource.RawText.ToLower()))
                    {
                        context.Succeed(requirement);
                        return;
                    }
                }
            }
        }
        context.Fail();
        return;
    }
}

stay  Startup The rest of the class doesn't change , Just add in  ConfigureServices Add the following code to the method , Through the injection of  PermissionHandler Class to replace with our processing class .

services.AddAuthorization(option => {
    //option.AddPolicy("adminOrSystem", policy => policy.RequireRole("admin", "system"));
    option.AddPolicy("Permission", policy => policy.AddRequirements(permissionRequirement));
});
services.AddSingleton<IAuthorizationHandler, PermissionHandler>();
//  Inject the authorization necessary classes into the life cycle 
services.AddSingleton(permissionRequirement);

Finally, you just need to add... To the interface or controller  [Authorize(Policy = "Permission")] That's all right. , Any interface access with this feature will follow our processing class  PermissionHandler Determine the relationship between the interface and the role , Thus, the requirement of dynamically setting interface and permission is realized .

My code here is relatively crude , At a minimum , You can perfect it according to your needs . You can also see the following reference article .

Reference article :

ASP.NET Core Use JWT Custom roles / The interface that policy authorization needs to implement

From the beginning, the front and the back end separate [.NetCore] 37 ║JWT Perfect dynamic allocation of permissions and interfaces

&n

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201206013033224d.html