In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the. Net core api interface how to achieve JWT authentication Token, the article is very detailed, has a certain reference value, interested friends must read it!
I. Project > manage Nuget package installation
2. Add "JWT": {"Secret": "~! @ # $% ^ & * () _ + qwertyuiopasldkh [o51485421ajshk ^% *) kasd", / / key "Issuer": "kfjdhf", / / issuer "Audience": "kfjdhf" / / recipient / / "Expired": 30 / / expiration time (30min)} 3. ConfigureServices injection jwt # region Registration JWT / / get configuration file var JWTConfig = Configuration.GetSection ("JWT") / / generate key var symmetricKeyAsBase64 = JWTConfig.GetValue ("Secret"); var keyByteArray = Encoding.ASCII.GetBytes (symmetricKeyAsBase64); var signingKey = new SymmetricSecurityKey (keyByteArray) / / Authentication parameter services.AddAuthentication ("Bearer") .AddJwtBearer (o = > {o.TokenValidationParameters = new TokenValidationParameters {ValidateIssuerSigningKey = true,// whether the signature is verified. Pictures that are not verified can tamper with the data. Unsecured IssuerSigningKey = signingKey,// decrypted key ValidateIssuer = true,// whether to verify the publisher, that is, to verify whether the Iss in the payload corresponds to the ValidIssuer parameter ValidIssuer = JWTConfig.GetValue ("Iss"), / / publisher ValidateAudience = true,// whether to verify the subscriber Is to verify whether the Aud in the payload corresponds to the ValidAudience parameter ValidAudience = JWTConfig.GetValue ("Aud"), / / whether the subscriber ValidateLifetime = true,// verifies the expiration time, and denies access to the expiration time if it expires. This is the buffer expiration time, that is, even if we configure the expiration time. Also take into account here, expiration time + buffer, the default is like 7 minutes, you can directly set to 0 RequireExpirationTime = true,} }); # endregion
(2) .configure enabled
App.UseAuthentication (); / / jwt 4. Create the jwt help class using Microsoft.Extensions.Configuration;using Microsoft.IdentityModel.Tokens;using System;using System.Collections.Generic;using System.IdentityModel.Tokens.Jwt;using System.Linq;using System.Security.Claims;using System.Text; namespace SystemAPi.JWT {public class JwtHelper {public JwtHelper (IConfiguration configuration) {Configuration = configuration } / configuration properties / public IConfiguration Configuration {get } / generate Token / public string GenerateToken (List claims) {var jwtConfig = Configuration.GetSection ("Jwt") / / the secret key, which is the header, is used here. Using the Hmacsha256 algorithm, the key of 256bit var securityKey = new SigningCredentials (new SymmetricSecurityKey (Encoding.ASCII.GetBytes (jwtConfig.GetValue ("Secret")), SecurityAlgorithms.HmacSha256) is required; / / many default parameter names are predefined in / / Claim,JwtRegisteredClaimNames, or you can define your own key names as shown in Guid below. / / ClaimTypes also predefines many types such as role, email, and name. Role is used to grant permissions Different roles can access different interfaces / / equivalent to the payload List baseClaims = new List {new Claim (JwtRegisteredClaimNames.Iss,jwtConfig.GetValue ("Issuer")), new Claim (JwtRegisteredClaimNames.Aud,jwtConfig.GetValue ("Audience")), new Claim ("Guid", Guid.NewGuid (). ToString ("D")) New Claim (ClaimTypes.Role, "admin"),} Claims = claims.Union (baseClaims). ToList (); / / merge Claim, delete duplicate items SecurityToken securityToken = new JwtSecurityToken (signingCredentials: securityKey, expires: DateTime.Now.AddDays (1), / / expiration claims: claims) / / generate jwt token return new JwtSecurityTokenHandler () .WriteToken (securityToken) 5. Test login and successfully store account information in token / / login / login [HttpGet] public ReturnJson login (string name, string pwd) {User data = bll.login (name, pwd) If (dataplanes null) {if (data.name = = name & & data.password = = pwd) {List claims = new List () {new Claim (ClaimTypes.NameIdentifier, data.name), new Claim (ClaimTypes.Role,data.AdminId.ToString ()) New Claim ("AdminRole", data.AdminId.ToString ())} String token=jwtHelper.GenerateToken (claims); return new ReturnJson (). Success (token);};} return new ReturnJson (). Fail ();}
The above is all the content of the article "how to achieve JWT authentication Token with. Net core api interface". Thank you for reading! Hope to share the content to help you, more related 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.
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.