. net # core # API interface JWT authentication token

Time:2022-4-29

1、 Project > manage nuget package installation

2、 appsettings. JSON add

"JWT": {
    "Secret": "~! @#$% ^ & * () qwertyuiopasldkh[o51485421ajshk ^% *) Kasd", // key
    "Issuer": "kfjdhf", // issuer
    "Audience": "kfjdhf", // receiver
    //"Expired": 30 // expiration time (30min)
  }

3、 Configureservices injection JWT

#Region register JWT
 
            //Get profile
            var JWTConfig = Configuration.GetSection("JWT");
            //Generate key
            var symmetricKeyAsBase64 = JWTConfig.GetValue<string>("Secret");
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);
 
            //Authentication parameters
            services.AddAuthentication("Bearer")
                .AddJwtBearer(o =>
                {
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        Validateissuersigningkey = true, // whether to verify the signature. Paintings that are not verified can tamper with data and are not safe
                        Issuersigningkey = signingkey, // decrypted key
                        Validateissuer = true, // whether to verify the publisher, that is, whether the issuers in the payload correspond to the validateissuer parameter
                        ValidIssuer = JWTConfig. GetValue < string > ("is"), // issuer
                        Validateaudience = true, // verify the subscriber, that is, verify whether the AUD in the payload corresponds to the validateaudience parameter
                        ValidAudience = JWTConfig. GetValue < string > ("aud"), // subscriber
                        Validatelifetime = true, // whether to verify the expiration time. If it expires, access will be denied
                        ClockSkew = TimeSpan. Zero, // this is the buffer expiration time, that is, even if we configure the expiration time, it should be taken into account here. Expiration time + buffer, which seems to be 7 minutes by default, and you can directly set it to 0
                        RequireExpirationTime = true,
                    };
                });
            #endregion

(2). Configure enable


app.UseAuthentication();//jwt

4、 Create 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;
            }
            /// <summary>
            ///Configuration properties
            /// </summary>
            public IConfiguration Configuration { get; }
            /// <summary>
            ///Generate token
            /// </summary>
            /// <returns></returns>
            public string GenerateToken(List<Claim> claims)
            {
                var jwtConfig = Configuration.GetSection("Jwt");
                //The secret key is the header. The hmacsha256 algorithm is used here. A 256 bit key is required
                var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.GetValue<string>("Secret"))), SecurityAlgorithms.HmacSha256);
                //Many default parameter names are predefined in claim and jwtregisteredclaimnames. You can also define your own key name like the following guid
                //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 payload
                List<Claim> baseClaims = new List<Claim>{
                new Claim(JwtRegisteredClaimNames.Iss,jwtConfig.GetValue<string>("Issuer")),
                new Claim(JwtRegisteredClaimNames.Aud,jwtConfig.GetValue<string>("Audience")),
                new Claim("Guid",Guid.NewGuid().ToString("D")),
                new Claim(ClaimTypes.Role,"admin"),
             };
                claims = claims. Union<Claim>(baseClaims). ToList<Claim>();// Merge claim and delete duplicate items
 
                SecurityToken securityToken = new JwtSecurityToken(
                    signingCredentials: securityKey,
                    expires: DateTime. Now. Adddays (1), // expiration time
                    claims: claims
                );
                //Generate JWT token
                return new JwtSecurityTokenHandler().WriteToken(securityToken);
            }
        }
    }

5、 The test login is successful. Save the account information into the token

///Login
        /// </summary>
        ///< returns > login < / returns >
        [HttpGet]
 
        public ReturnJson login(string name, string pwd)
        {
            
            User data = bll.login(name, pwd);
            if (data!=null)
            {
                if (data.name == name && data.password == pwd)
                {
                    List<Claim> claims = new List<Claim>() {
                    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<string>().Success(token);                  
                    
                };
              
            }
            return new ReturnJson().Fail();
        }

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.