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

What is the method for ASP.NET Core 3.0 lightweight role API to control the authorization library

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

Share

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

This article editor for everyone to introduce in detail "ASP.NET Core 3.0 lightweight role API control authorization library method is what", the content is detailed, the steps are clear, the details are handled properly, hope that this "ASP.NET Core 3.0 lightweight role API control authorization library method is what" article can help you solve doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.

Description

ASP.NET Core 3.0A lightweight role / user of jwt, an authorization library controlled by a single API

ASP.NET Core uses the interface that JWT custom role / policy authorization needs to implement, and uses Microsoft's own authorization authentication to expand on this basis. The feature is that it is very easy to use and does not need too much configuration; because there is no "building wheel", it is also very simple if it needs to be modified.

This library has been updated to .net Core 3.0. if you need to use it on 2.2X, you can download the project from the warehouse and replace the Nuget package with 2.2.

Define roles, API, and users

Casually create a new website or API project, such as MyAuth.

Search for CZGL.Auth in Nuget according to version 2.0.1, or use the Package Manager command

Install-Package CZGL.Auth-Version 2.0.1

The CZGL.Auth design idea is that a website can have multiple roles, multiple users, and multiple API.

A role has some API, and you can add or remove roles or modify the API accessed by role ownership

A user can belong to several roles at the same time.

The first step is to consider the role, user and API design of the website.

CZGL.Auth stores this information in memory, which roles a user has and what API access permissions a role has.

There is a corresponding relationship between roles and API, and there is a many-to-many relationship between users and roles.

Create a new class RoleService.cs and introduce using CZGL.Auth.Services;,RoleService inheritance ManaRole.

Manipulate role permission information through the following interfaces

Protected bool AddRole (RoleModel role); protected bool AddUser (UserModel user); protected bool RemoveRole (string roleName); protected bool RemoveUser (string userName)

Obviously, add / remove a role, add / remove a user

If there are three roles A, B and C

There are 7 API of / A, / B, / C, / AB, / AC, / BC, / ABC to set permissions.

A can visit A, AB, AC, ABC

B can visit B, AB, BC, ABC

C can visit C, AC, BC, ABC

The method of simulating data is used here, and the actual data is not loaded from the database.

Add a method to RoleService

/ used to load roles and API / public void UpdateRole () {List roles = new List {new RoleModel {RoleName= "A" Apis=new List {new OneApiModel {ApiName= "A", ApiUrl= "/ A"} New OneApiModel {ApiName= "AB", ApiUrl= "/ AB"}, new OneApiModel {ApiName= "AC" ApiUrl= "/ AC"}, new OneApiModel {ApiName= "ABC", ApiUrl= "/ ABC"} New RoleModel {RoleName= "B", Apis=new List {new OneApiModel {ApiName= "B" ApiUrl= "/ B"}, new OneApiModel {ApiName= "AB", ApiUrl= "/ AB"} New OneApiModel {ApiName= "BC", ApiUrl= "/ BC"}, new OneApiModel {ApiName= "ABC" ApiUrl= "/ ABC"}, new RoleModel {RoleName= "A" Apis=new List {new OneApiModel {ApiName= "A", ApiUrl= "/ A"} New OneApiModel {ApiName= "AB", ApiUrl= "/ AB"}, new OneApiModel {ApiName= "AC" ApiUrl= "/ AC"}, new OneApiModel {ApiName= "ABC" ApiUrl= "/ ABC"} Foreach (var item in roles) {AddRole (item);}}

With the roles and corresponding API information, it's time to add users.

Suppose there are three users: aa, bb and cc. The passwords are all 123456, and AA belongs to role An and bb belongs to role B.

Public void UpdateUser () {AddUser (new UserModel {UserName = "aa", BeRoles = new List {"A"}); AddUser (new UserModel {UserName = "bb", BeRoles = new List {"B"}}); AddUser (new UserModel {UserName = "cc", BeRoles = new List {"C"}});}

To be able to load roles and users into CZGL.Auth, you need to use the

RoleService roleService = new RoleService (); roleService.UpdateRole (); roleService.UpdateUser (); II. Add custom events

Authorization is, there may be a variety of situations, you can add custom events to record the authorization information accessed by the user, affecting the authorization result.

Quote using CZGL.Auth.Interface

Add a class RoleEvents inherits IRoleEventsHadner

Public class RoleEvents: IRoleEventsHadner {public async Task Start (HttpContext httpContext) {await Task.CompletedTask } public void TokenEbnormal (object eventsInfo) {} public void TokenIssued (object eventsInfo) {} public void NoPermissions (object eventsInfo) {} public void Success (object eventsInfo) {} public async Task End (HttpContext httpContext) {await Task.CompletedTask;}}

Call Start before CZGL.Auth starts to verify authorization, and call End at the end. The passed-in parameter is HttpContext. You can add custom authorization information to it, which can affect the request pipeline.

Several other methods have the following implications:

The Token carried by the TokenEbnormal client is not a valid Jwt token and will not be parsed

Issuer or audience is incorrect after TokenIssued token decoding

NoPermissions does not have access to this API

The above method will be called at all stages of authorization authentication.

III. Injection of authorization services and middleware

To use CZGL.Auth, you need to inject the following two services

Services.AddRoleService (authOptions); services.AddSingleton ()

AddRoleService is the injection authorization service, and AddSingleton injects your events.

AddRoleService requires an AuthConfigModel type as a parameter.

You can configure it like this.

Var authOptions = new AuthBuilder () .Security ("aaaafsfsfdrhdhrejtrjrt", "ASPNETCORE", "ASPNETCORE") .Jump ("accoun/login", "account/error", false, false) .time (TimeSpan.FromMinutes (20)) .InfoScheme (new CZGL.Auth.Models.AuthenticateScheme {TokenEbnormal = "Login authentication failed!" TokenIssued = "Login authentication failed!", NoPermissions = "Login authentication failed!"}) .Build () Services.AddRoleService (authOptions); services.AddSingleton ()

Security configures key-related parameters: key string, issuer, and subscriber.

When Jump configuration authorization fails, jump to the address. The parameters are unauthorized jump and invalid authorization jump, respectively. The last two bool can be set to jump or jump.

Time configures the Token validity period.

InfoScheme authorization failure message, such as

The above figure shows the message that the time expires. If the user fails to request API, a 401 status code will be returned. Header will carry the prompt message. In CZGL.Auth, the header is customized in three cases:

The Token carried by the TokenEbnormal client is not a valid Jwt token and will not be parsed

Issuer or audience is incorrect after TokenIssued token decoding

NoPermissions does not have access to this API

Add three middleware

App.UseAuthentication (); app.UseAuthorization (); app.UseMiddleware ()

App.UseAuthorization (); is Microsoft's authorization middleware. CZGL.Auth will first let the default authentication pipeline filter some invalid requests and authentication information, and then CZGL.Auth will verify the authorization.

How to set the authorization of API

Very simple, CZGL.Auth authentication authorization, you just need to add [Authorize] to Controller or Action.

CZGL.Auth only works on Controller or Action that use the [Authorize] feature.

If a Controller has been set [Authorize], but you want the Action in it to skip authorization authentication, use [AllowAnonymous] to modify the Action.

The method of use is exactly the same as Microsoft's default. This does not require too much configuration.

If you want to define another feature to set up another license, you can mention Issue to my warehouse or contact me Wechat directly.

Add an APIController

[Authorize] [Route ("api/ [controller]")] [ApiController] public class TestController: ControllerBase {[HttpGet ("/ A")] public JsonResult A () {return new JsonResult (new {Code = 200, Message = "Success!"}) } [HttpGet ("/ B")] public JsonResult B () {return new JsonResult (new {Code = 200, Message = "Success!"});} [HttpGet ("/ C")] public JsonResult C () {return new JsonResult (new {Code = 200, Message = "Success!"}) } [HttpGet ("/ AB")] public JsonResult AB () {return new JsonResult (new {Code = 200, Message = "Success!"});} [HttpGet ("/ BC")] public JsonResult BC () {return new JsonResult (new {Code = 200, Message = "Success!"}) } [HttpGet ("/ AC")] public JsonResult AC () {return new JsonResult (new {Code = 200, Message = "Success!"});} [HttpGet ("/ ABC")] public JsonResult ABC () {return new JsonResult (new {claims = User.Claims}) } / / No one can access / [HttpGet ("D")] public JsonResult D () {return new JsonResult (new {Code = 200, Message = "Success!"}) } [HttpGet ("error")] public JsonResult Denied () {return new JsonResult (new {Code = 0, Message = "access failed!", Data = "this account does not have access!" 5. Add login and issue Token

Add an AccountController.cs to issue login, Token.

[Route ("api/ [controller]")] [ApiController] public class AccountController: ControllerBase {[HttpPost ("/ Login")] public async Task Login ([FromQuery] string username, string password String rolename) {/ / whether the user name password is correct if (string.IsNullOrWhiteSpace (username) | | string.IsNullOrWhiteSpace (password) | | string.IsNullOrWhiteSpace (rolename)) {return new JsonResult (new {Code = 0, Message = "Nima") What spam messages are uploaded ",}) } if (! ((username== "aa" | | username== "bb" | | username== "cc") & & password== "123456") {return new JsonResult (new {Code = 0, Message = "account or password error",}) } / / your own defined role / user information service RoleService roleService = new RoleService (); / / verify whether the user belongs to this role var role = roleService.IsUserToRole (username,rolename); / / A class EncryptionHash hash = new EncryptionHash () in CZGL.Auth for encryption and decryption / / set user ID var userClaims = hash.BuildClaims (username, rolename) / Custom build configuration user ID / / customized Contains at least the following identities / / var userClaims = new Claim [] / / {/ / new Claim (ClaimTypes.Name, userName), / / new Claim (ClaimTypes.Role, roleName), / / new Claim (JwtRegisteredClaimNames.Aud, Audience), / / new Claim (ClaimTypes.Expiration, TimeSpan.TotalSeconds.ToString ()) / / new Claim (JwtRegisteredClaimNames.Iat, new DateTimeOffset (DateTime.Now). ToUnixTimeSeconds (). ToString ()) / /} / * iss (issuer): issuer exp (expiration time): expiration time sub (subject): subject aud (audience): audience nbf (Not Before): effective time iat (Issued At): issue time jti (JWT ID): number * / / method 1 Issue Token ResponseToken token = hash.BuildToken (userClaims) directly / / method 2, split multiple steps and issue token for easy debugging / / var identity = hash.GetIdentity (userClaims); / / var jwt = hash.BuildJwtToken (userClaims); / / var token = hash.BuildJwtResponseToken (jwt); return new JsonResult (token);}} VI.

Inject Jwt services, issue Token

CZGL.Auth encapsulates the service that uses jwt and the code that issues Token, and this library is not "building wheels", so you can actually easily extract this part of the code and design it separately.

The location of the code for this part is RoleServiceExtension.cs, EncryptionHash.cs.

Authorized middleware

App.UseAuthentication (); app.UseAuthorization (); app.UseMiddleware ()

My way of writing is to use ASP.NET Core's jwt to complete the basic authentication authorization, and then achieve the extended authentication in the next pipeline. But its own authentication is in app.UseAuthorization (); has been expanded, so the use of CZGL.Auth, only need to follow the usual way of jwt to use, only add a RoleMiddleware middleware.

CZGL.Auth is just something I wrote on an ad hoc basis inspired by new ideas. It's best not to use it directly in production. Go to the github library to download the project and change it according to your own application scenario.

VII. Verification

Log in using the aa user first, and select the A role when logging in.

Because A users can only access "API with A", "/ A", "/ AB", etc., so we can try.

Continue to visit "/ B" with this Token.

You can continue to try to add API or log in with another user to access a different API.

Because others are not familiar with the front end, they will not write an example with a page.

You can test it with Postman.

What sample project can be downloaded from the warehouse, the name is MyAuth.

Generally speaking, the information of user permissions and role permissions is stored in the database. Another example is CZGL.Auth.Sample2.

Read this, the "ASP.NET Core 3.0 lightweight role API control authorization library what is the method" article has been introduced, want to master the knowledge of this article still need to practice and use in order to understand, if you want to know more about the article, 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