In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
ASP.NET Core how to use JWT custom roles and implement policy authorization required interfaces, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
① stores the API that roles / users can access
For example
Use List to store a list of authorized API for roles.
not essential.
The authorized API can be stored in the Token, or the Token can only store role information and user identity information.
/ API / public class ApiPermission {/ API name / public virtual string Name {get; set;} / API address / public virtual string Url {get; set;}} ② implements the IAuthorizationRequirement interface
The IAuthorizationRequirement interface represents the user's identity information and is used for authentication and authorization verification.
In fact, IAuthorizationRequirement has nothing to implement.
Namespace Microsoft.AspNetCore.Authorization {/ abstract: / / Represents an authorization requirement. Public interface IAuthorizationRequirement {}}
To implement IAuthorizationRequirement, you can define the properties you want at will, which will be used as a convenient means of custom validation.
Depending on how to use it, you can define it as a global identity and set global common data.
I later found that my way of writing was not very good:
/ / IAuthorizationRequirement is the necessary parameter class for Microsoft.AspNetCore.Authorization interface / user authentication information / public class PermissionRequirement: IAuthorizationRequirement {/ user role / public Role Roles {get; set;} = new Role (); public void SetRolesName (string roleName) {Roles.Name = roleName } / unlimited time jump to this API / public string DeniedAction {get; set;} / public string ClaimType authorization type / public string ClaimType {internal get; set } / public string LoginPath {get; set;} = "/ Account/Login"; / public string Issuer {get; set;} / subscriber / public string Audience {get; set } / Expiration time / public TimeSpan Expiration {get; set;} / issue time / public long IssuedTime {get; set;} / signature verification / public SigningCredentials SigningCredentials {get; set } / construct / No permission to jump to this API / / user permission set / url / / permission set of rejection request / declare type / / publisher / subscriber / / issue time / / signature verification entity public PermissionRequirement (string deniedAction Role Role, string claimType, string issuer, string audience, SigningCredentials signingCredentials,long issusedTime, TimeSpan expiration) {ClaimType = claimType DeniedAction = deniedAction; Roles = Role; Issuer = issuer; Audience = audience; Expiration = expiration; IssuedTime = issusedTime; SigningCredentials = signingCredentials;}} ③ to implement TokenValidationParameters
Information configuration of Token
Public static TokenValidationParameters GetTokenValidationParameters () {var tokenValida = new TokenValidationParameters {/ / define Token content ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey (Encoding.UTF8.GetBytes (AuthConfig.SecurityKey)), ValidateIssuer = true, ValidIssuer = AuthConfig.Issuer, ValidateAudience = true ValidAudience = AuthConfig.Audience, ValidateLifetime = true, ClockSkew = TimeSpan.Zero, RequireExpirationTime = true} Return tokenValida;} ④ generates Token
Used to store the user's identity information (Claims) and role authorization information (PermissionRequirement) in the Token.
/ get JWT-based Token / public static dynamic BuildJwtToken (Claim [] claims, PermissionRequirement permissionRequirement) {var now = DateTime.UtcNow Var jwt = new JwtSecurityToken (issuer: permissionRequirement.Issuer, audience: permissionRequirement.Audience, claims: claims, notBefore: now, expires: now.Add (permissionRequirement.Expiration), signingCredentials: permissionRequirement.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler () .WriteToken (jwt) Var response = new {Status = true, access_token = encodedJwt, expires_in = permissionRequirement.Expiration.TotalMilliseconds, token_type = "Bearer"}; return response;} ⑤ implements service injection and authentication configuration
Import configuration information from other variables, optional
/ / set the key used to encrypt Token / / configure role permissions var roleRequirement = RolePermission.GetRoleRequirement (AccountHash.GetTokenSecurityKey ()); / / define how to generate the user's Token var tokenValidationParameters = RolePermission.GetTokenValidationParameters ()
Configure the authentication service for ASP.NET Core
Three configurations need to be implemented
AddAuthorization imports role authentication policy
AddAuthentication authentication type
AddJwtBearer Jwt authentication configuration
/ / Import role authentication policy services.AddAuthorization (options = > {options.AddPolicy ("Permission", policy = > policy.Requirements.Add (roleRequirement)); / / ↓ authentication type}) .AddAuthentication (options = > {options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme) Options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; / / ↓ Jwt authentication configuration}) .AddJwtBearer (options = > {options.TokenValidationParameters = tokenValidationParameters; options.SaveToken = true) Options.Events = new JwtBearerEvents () {/ / call after the security token is authenticated and ClaimsIdentity is authenticated / / if the user visits the logout page OnTokenValidated = context = > {if (context) .Request.Path.Value.ToString () = = "/ account/logout") {var token = ((context as TokenValidatedContext) .SecurityToken as JwtSecurityToken) .RawData } return Task.CompletedTask;};)
Inject custom authorization service PermissionHandler
Inject the custom authentication model class roleRequirement
/ / add httpcontext intercept services.AddSingleton (); services.AddSingleton (roleRequirement)
Add middleware
See an example like this on Microsoft's official website. But my test found that the client carried Token information, the request to pass the validation context, or failed, so the use will return 403.
App.UseAuthentication (); app.UseAuthorization ()
Found that this is the only way to OK:
App.UseAuthorization (); app.UseAuthentication (); ⑥ to achieve login
You can store the API you can use when issuing Token, but this approach is not suitable for situations with more API.
User information (Claims) and role information can be stored, and the background can obtain the API list authorized to access through the role information.
/ login / username / / password / Token information [HttpPost ("login")] public JsonResult Login (string username, string password) {var user = UserModel.Users.FirstOrDefault (x = > x.UserName = = username & & x.UserPossword = = password) If (user = = null) return new JsonResult (new ResponseModel {Code = 0, Message = "login failed!"}) / / configure user ID var userClaims = new Claim [] {new Claim (ClaimTypes.Name,user.UserName), new Claim (ClaimTypes.Role,user.Role), new Claim (ClaimTypes.Expiration,DateTime.Now.AddMinutes (_ requirement.Expiration.TotalMinutes). ToString ()),} _ requirement.SetRolesName (user.Role); / / generate user ID var identity = new ClaimsIdentity (JwtBearerDefaults.AuthenticationScheme); identity.AddClaims (userClaims); var token = JwtToken.BuildJwtToken (userClaims, _ requirement) Return new JsonResult (new ResponseModel {Code = 200,200, Message = "login succeeded! Please make sure to save your Token credentials! ", Data = token});} ⑦ add API authorization policy [Authorize (Policy =" Permission ")] ⑧ to implement custom authorization verification
To implement custom API role / policy authorization, you need to inherit AuthorizationHandler.
The content is completely customized, and AuthorizationHandlerContext is the context of authentication authorization, where custom access authorization authentication is implemented.
You can also add the ability to automatically refresh Token.
/ verify user information and authorize Handler / public class PermissionHandler: AuthorizationHandler {protected override Task HandleRequirementAsync (AuthorizationHandlerContext context, PermissionRequirement requirement) {List requirements = new List () Foreach (var item in context.Requirements) {requirements.Add ((PermissionRequirement) item);} foreach (var item in requirements) {/ / verify the issuing and receiving object if (! (item.Issuer = = AuthConfig.Issuer? Item.Audience = = AuthConfig.Audience? True: false: false) {context.Fail ();} / / verify expiration time var nowTime = DateTimeOffset.Now.ToUnixTimeSeconds (); var issued = item.IssuedTime + Convert.ToInt64 (item.Expiration.TotalSeconds); if (issued)
< nowTime) context.Fail(); // 是否有访问此 API 的权限 var resource = ((Microsoft.AspNetCore.Routing.RouteEndpoint)context.Resource).RoutePattern; var permissions = item.Roles.Permissions.ToList(); var apis = permissions.Any(x =>X.Name.ToLower () = = item.Roles.Name.ToLower () & & x.Url.ToLower () = = resource.RawText.ToLower ()); if (! apis) context.Fail (); context.Succeed (requirement); / / Jump to a page for unlimited time / / var httpcontext = new HttpContextAccessor () / / httpcontext.HttpContext.Response.Redirect (item.DeniedAction);} context.Succeed (requirement); return Task.CompletedTask;}} ⑨ some useful code
Generates a hash of the string, such as a password.
For security, delete special characters in the string, such as ",', $.
Public static class AccountHash {/ / gets the hash value of the string public static string GetByHashString (string str) {string hash = GetMd5Hash (str.Replace ("\", String.Empty) .replace ("\", String.Empty) .replace ("$", String.Empty)); return hash } / get the key used to encrypt Token / public static SigningCredentials GetTokenSecurityKey () {var securityKey = new SigningCredentials (new SymmetricSecurityKey (Encoding.UTF8.GetBytes (AuthConfig.SecurityKey)), SecurityAlgorithms.HmacSha256); return securityKey } private static string GetMd5Hash (string source) {MD5 md5Hash = MD5.Create (); byte [] data = md5Hash.ComputeHash (Encoding.UTF8.GetBytes (source)); StringBuilder sBuilder = new StringBuilder (); for (int I = 0; I < data.Length; iTunes +) {sBuilder.Append (data [I] .ToString ("x2")) } return sBuilder.ToString ();}}
Issue Token
PermissionRequirement is not required, used to store role or policy authentication information, Claims should be necessary.
/ issue user Token / public class JwtToken {/ get JWT-based Token / public static dynamic BuildJwtToken (Claim [] claims, PermissionRequirement permissionRequirement) {var now = DateTime.UtcNow Var jwt = new JwtSecurityToken (issuer: permissionRequirement.Issuer, audience: permissionRequirement.Audience, claims: claims, notBefore: now, expires: now.Add (permissionRequirement.Expiration), signingCredentials: permissionRequirement.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler () .WriteToken (jwt) Var response = new {Status = true, access_token = encodedJwt, expires_in = permissionRequirement.Expiration.TotalMilliseconds, token_type = "Bearer"}; return response;}
Represents a timestamp
/ / Unix timestamp DateTimeOffset.Now.ToUnixTimeSeconds (); / verify whether Token expires / / convert TimeSpan to Unix timestamp Convert.ToInt64 (TimeSpan); DateTimeOffset.Now.ToUnixTimeSeconds () + Convert.ToInt64 (TimeSpan); what is ASP.NET? ASP.NET is an open source, cross-platform, high-performance, lightweight Web application building framework that is often used to build web pages and websites through HTML, CSS, JavaScript and server scripts.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.