Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Policy Authorization and ABP Authorization in ASP.NET Core

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to use policy authorization and ABP authorization in ASP.NET Core, I believe most people do not know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's learn about it together.

Policy Authorization in ASP.NET Core

First, let's create a WebAPI application.

Then introduce the Microsoft.AspNetCore.Authentication.JwtBearer package.

strategy

In the ConfigureServices method of the Startup class, add a policy in the following form:

Services.AddAuthorization (options = > {options.AddPolicy ("AtLeast21", policy = > policy.Requirements.Add (new MinimumAgeRequirement (21));})

Let's talk about it step by step.

Services.AddAuthorization is used to add authorization methods. Currently, only AddPolicy is supported.

In ASP.NET Core, there are three forms of authorization based on role, declaration, and policy, all of which use AddPolicy to add authorization processing.

Among them, two API are as follows:

Public void AddPolicy (string name, AuthorizationPolicy policy); public void AddPolicy (string name, Action configurePolicy)

Name = "AtLeast21", where "AtLeast21" is the name of the policy.

Policy.Requirements.Add () is used to add a tag for a policy (to store data for this policy), which needs to inherit the IAuthorizationRequirement interface.

How should the name of the policy be set? How should I write a policy on authorization and use Requirements.Add ()?

Let's put it down here for a while, and we'll explain it next.

Define a Controller

Let's add a Controller:

[ApiController] [Route ("[controller]")] public class BookController: ControllerBase {private static List BookContent = new List (); [HttpGet ("Add")] public string AddContent (string body) {BookContent.Add (body); return "success" } [HttpGet ("Remove")] public string RemoveContent (int n) {BookContent.Remove (Bookcontent [n]); return "success";} [HttpGet ("Select")] public List SelectContent () {List obj = new List (); int I = 0 Foreach (var item in BookContent) {int tmp = I; iTunes; obj.Add (new {Num = tmp, Body = item});} return obj;} [HttpGet ("Update")] public string UpdateContent (int n, string body) {BookContent [n] = body Return "success";}}

The function is very simple, that is, to add, delete, check and change the contents of the list.

Set permissions

Earlier, we created BookController, which has the function of adding, deleting, checking and modifying. A permission should be set for each function.

In ASP.NET Core, a permission tag that needs to inherit the IAuthorizationRequirement interface.

Let's set up five permissions:

Add a file and fill in the following code.

/ * IAuthorizationRequirement is an empty interface. For authorization requirements, its attributes and other information are customized and the inheritance relationship here does not make any sense * / / the permission to access Book public class BookRequirment: IAuthorizationRequirement {} / / add, delete, query and modify Book permissions / / can inherit IAuthorizationRequirement You can also inherit BookRequirment public class BookAddRequirment: BookRequirment {} public class BookRemoveRequirment: BookRequirment {} public class BookSelectRequirment: BookRequirment {} public class BookUpdateRequirment: BookRequirment {}

The BookRequirment representative can access the BookController, and the other four represent the permission to add, delete, check and correct.

Define a policy

After the permissions are set, we begin to set the policy.

In the ConfigureServices of Startup, add:

Services.AddAuthorization (options = > {options.AddPolicy ("Book", policy = > {policy.Requirements.Add (new BookRequirment ());}); options.AddPolicy ("Book:Add", policy = > {policy.Requirements.Add (new BookAddRequirment () }); options.AddPolicy ("Book:Remove", policy = > {policy.Requirements.Add (new BookRemoveRequirment ());}); options.AddPolicy ("Book:Select", policy = > {policy.Requirements.Add (new BookSelectRequirment () }); options.AddPolicy ("Book:Update", policy = > {policy.Requirements.Add (new BookUpdateRequirment ());});})

Here we only set one permission for each policy, of course, each policy can add multiple permissions.

Here the name is used: separation, mainly for readability, so that people can see that it is a hierarchical relationship.

Store user information

Here, for simplicity, the database is not used.

The following user information structure is written casually. User-role-permissions that the role has.

This permission can be stored in any type. As long as you can identify which permission it is.

/ storing user information / public static class UsersData {public static readonly List Users = new List () Static UsersData () {/ / add an administrator Users.Add (new User {Name = "admin", Email = "admin@admin.com") Role = new Role {Requirements = new List {typeof (BookRequirment), typeof (BookAddRequirment), typeof (BookRemoveRequirment), typeof (BookSelectRequirment) Typeof (BookUpdateRequirment)}) / / No permission to delete Users.Add (new User {Name = "author", Email = "wirter", Role = new Role {Requirements = new List {typeof (BookRequirment)) Typeof (BookAddRequirment), typeof (BookRemoveRequirment), typeof (BookSelectRequirment),}) }} public class User {public string Name {get; set;} public string Email {get; set;} public Role Role {get; set } / the policy authorization of the storage role here, string numbers, etc. As long as the storage representation can be stored, OK / has no meaning here, it's just a way to identify / public class Role {public List Requirements {get; set;}} mark access rights.

Once the policy has been defined, it is time to mark access for Controller and Action.

Use the [Authorize (Policy = "{string}")] attributes and properties to set the permissions required to access this Controller and Action.

Here we set it separately, with each function marked with a permission (the minimum granularity should be a function, not an API).

[Authorize (Policy = "Book")] [ApiController] [Route ("[controller]")] public class BookController: ControllerBase {private static List BookContent = new List () [Authorize (Policy = "Book:Add")] [HttpGet ("Add")] public string AddContent (string body) {} [Authorize (Policy = "Book:Remove")] [HttpGet ("Remove")] public string RemoveContent (int n) {} [Authorize (Policy = "Book:Select")] [HttpGet ("Select")] public List SelectContent () { } [Authorize (Policy = "Book:Update")] [HttpGet ("Update")] public string UpdateContent (int n String body) {}} Authentication: Token credential

Because you are using WebAPI, you can use Bearer Token authentication, of course, you can use Cookie and so on. You can use any kind of authentication.

/ / set the verification method to Bearer Token / / add using Microsoft.AspNetCore.Authentication.JwtBearer / / you can also use the string "Brearer" instead of JwtBearerDefaults.AuthenticationScheme services.AddAuthentication (JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer (options = > {options.TokenValidationParameters = new TokenValidationParameters {ValidateIssuerSigningKey = true) IssuerSigningKey = new SymmetricSecurityKey (Encoding.UTF8.GetBytes ("abcdABCD1234abcdABCD1234")), / / key for encryption and decryption of Token / / whether to verify the publisher ValidateIssuer = true, / / publisher name ValidIssuer = "server" / / whether to verify the subscriber / / subscriber name ValidateAudience = true, ValidAudience = "client007", / / whether to verify the token validity period ValidateLifetime = true / / each time a token is issued Token validity time ClockSkew = TimeSpan.FromMinutes })

The above code is a template that can be changed at will. The authentication method here has nothing to do with our policy authorization.

Issue login credentials

The following Action is placed in BookController as a login function. This part is also not important, mainly to issue credentials to the user and to identify the user. A user's Claim can store a unique identity for this user.

/ user logs in and issues credentials / [AllowAnonymous] [HttpGet ("Token")] public string Token (string name) {User user = UsersData.Users.FirstOrDefault (x = > x.Name.Equals (name, StringComparison.OrdinalIgnoreCase)) If (user is null) return "this user not found"; / / define user information var claims = new Claim [] {new Claim (ClaimTypes.Name, name), new Claim (JwtRegisteredClaimNames.Email, user.Email)} / / consistent with the configuration in Startup SymmetricSecurityKey key = new SymmetricSecurityKey (Encoding.UTF8.GetBytes ("abcdABCD1234abcdABCD1234")) JwtSecurityToken token = new JwtSecurityToken (issuer: "server", audience: "client007", claims: claims, notBefore: DateTime.Now, expires: DateTime.Now.AddMinutes (30), signingCredentials: new SigningCredentials (key, SecurityAlgorithms.HmacSha256)) String jwtToken = new JwtSecurityTokenHandler () .WriteToken (token); return jwtToken;}

The following two lines are added to Configure:

App.UseAuthentication (); app.UseAuthorization (); Custom authorization

Custom authorization needs to inherit the IAuthorizationHandler interface, and the class that implements this interface can decide whether to authorize the user's access.

The implementation code is as follows:

/ determine whether the user has permissions / public class PermissionHandler: IAuthorizationHandler {public async Task HandleAsync (AuthorizationHandlerContext context) {/ / the permissions required to access Controller/Action (policy authorization) IAuthorizationRequirement [] pendingRequirements = context.PendingRequirements.ToArray (); / / fetch user information IEnumerable claims = context.User?.Claims / / not logged in or cannot get the user information if (claims is null) {context.Fail (); return;} / / take out the user name Claim userName = claims.FirstOrDefault (x = > x.Type = = ClaimTypes.Name) If (userName is null) {context.Fail (); return;} / /. Omit some verification process. / / get the information of this user User user = UsersData.Users.FirstOrDefault (x = > x.Name.Equals (userName.Value, StringComparison.OrdinalIgnoreCase)); List auths = user.Role.Requirements / / check foreach (IAuthorizationRequirement requirement in pendingRequirements) one by one {/ / if this permission is not found in the user permission list, if (! auths.Any (x = > x = = requirement.GetType ()) context.Fail (); context.Succeed (requirement) } await Task.CompletedTask;}}

Process:

Get user information from context (Context) (context.User)

Get the role to which this user belongs and get the permissions that this role has

Get the permissions (context.PendingRequirements) required for the Controller/Action of this request

Check the required permissions (foreach loop), and whether this user has

Finally, you need to register this interface and service in the container:

Services.AddSingleton ()

After you have done this, you can test the authorization.

IAuthorizationService

The class that implemented the IAuthorizationHandler interface earlier is used to customize to determine whether the user has access to this Controller/Action.

API IAuthorizationService is used to determine whether authorization is successful or not, which is defined as follows:

Public interface IAuthorizationService {Task AuthorizeAsync (ClaimsPrincipal user, object? Resource, IEnumerable requirements); Task AuthorizeAsync (ClaimsPrincipal user, object? Resource, string policyName);}

The DefaultAuthorizationService API implements IAuthorizationService, and ASP.NET Core uses DefaultAuthorizationService by default to confirm authorization.

Earlier, we used the IAuthorizationHandler interface to customize authorization, and if we go further, it goes back to IAuthorizationService.

DefaultAuthorizationService is the default implementation of IAuthorizationService, with a section of code as follows:

DefaultAuthorizationService is more complex, and in general, all we have to do is implement IAuthorizationHandler.

Reference: https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.authorization.defaultauthorizationservice?view=aspnetcore-3.1

ABP authorization

We have already introduced the policy authorization in ASP.NET Core, so let's take a look at the authorization in ABP, and let's continue to take advantage of the ASP.NET Core code that we implemented earlier.

Create an ABP application

Nuget installs Volo.Abp.AspNetCore.Mvc and Volo.Abp.Autofac.

Create the AppModule class as follows:

[DependsOn (typeof (AbpAspNetCoreMvcModule))] [DependsOn (typeof (AbpAutofacModule))] public class AppModule: AbpModule {public override void OnApplicationInitialization (ApplicationInitializationContext context) {var app = context.GetApplicationBuilder (); var env = context.GetEnvironment (); if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage () } else {app.UseExceptionHandler ("/ Error");} app.UseStaticFiles (); app.UseRouting (); app.UseConfiguredEndpoints ();}}

Add .UseServiceProviderFactory (new AutofacServiceProviderFactory ()) to the Host of Program, and the example is as follows:

Public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args) .UseServiceProviderFactory (new AutofacServiceProviderFactory ()).

Then in the ConfiguraServices method in Startup, add the ABP module and set it to use Autofac.

Public void ConfigureServices (IServiceCollection services) {services.AddApplication (options= > {options.UseAutofac ();});} define permissions

Use the PermissionDefinitionProvider class in ABP to define permissions and create a class with the following code:

Public class BookPermissionDefinitionProvider: PermissionDefinitionProvider {public override void Define (IPermissionDefinitionContext context) {var myGroup = context.AddGroup ("Book"); var permission = myGroup.AddPermission ("Book"); permission.AddChild ("Book:Add"); permission.AddChild ("Book:Remove"); permission.AddChild ("Book:Select"); permission.AddChild ("Book:Update") }}

A group Book is defined here, and a permission Book is defined, and Book has four sub-permissions under it.

Delete services.AddAuthorization (options = >...) from Startup.

Move the rest of the dependency injection service code to the ConfigureServices of AppModule.

The Configure of Startup is changed to:

App.InitializeApplication ()

Change the Configure in AbpModule to:

Var app = context.GetApplicationBuilder (); var env = context.GetEnvironment (); if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage ();} else {app.UseExceptionHandler ("/ Error");} app.UseStaticFiles (); app.UseRouting () App.UseAuthentication (); app.UseAuthorization (); app.UseConfiguredEndpoints ()

PermissionHandler needs to be changed to:

Public class PermissionHandler: IAuthorizationHandler {public Task HandleAsync (AuthorizationHandlerContext context) {/ / current permissions (policy authorization) IAuthorizationRequirement [] pendingRequirements = context.PendingRequirements.ToArray (); / / check foreach (IAuthorizationRequirement requirement in pendingRequirements) {context.Succeed (requirement) one by one } return Task.CompletedTask;}}

Delete the UserData file; BookController needs to modify the login and credentials.

The above is all the contents of this article entitled "how to use Policy Authorization and ABP Authorization in ASP.NET Core". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report