.net core api接口JWT方式認證Token

一、項目>管理Nuget包 安裝

二、.appsettings.json添加

"JWT": {
    "Secret": "~!@#$%^&*()_+qwertyuiopasldkh[o51485421ajshk^%*)kasd", // 密鑰
    "Issuer": "kfjdhf", // 頒發者
    "Audience": "kfjdhf", // 接收者
    //"Expired": 30 // 過期時間(30min)
  }

三、ConfigureServices註入jwt

 #region 註冊JWT
 
            //獲取配置文件
            var JWTConfig = Configuration.GetSection("JWT");
            //生成密鑰
            var symmetricKeyAsBase64 = JWTConfig.GetValue<string>("Secret");
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);
 
            //認證參數
            services.AddAuthentication("Bearer")
                .AddJwtBearer(o =>
                {
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,//是否驗證簽名,不驗證的畫可以篡改數據,不安全
                        IssuerSigningKey = signingKey,//解密的密鑰
                        ValidateIssuer = true,//是否驗證發行人,就是驗證載荷中的Iss是否對應ValidIssuer參數
                        ValidIssuer = JWTConfig.GetValue<string>("Iss"),//發行人
                        ValidateAudience = true,//是否驗證訂閱人,就是驗證載荷中的Aud是否對應ValidAudience參數
                        ValidAudience = JWTConfig.GetValue<string>("Aud"),//訂閱人
                        ValidateLifetime = true,//是否驗證過期時間,過期瞭就拒絕訪問
                        ClockSkew = TimeSpan.Zero,//這個是緩沖過期時間,也就是說,即使我們配置瞭過期時間,這裡也要考慮進去,過期時間+緩沖,默認好像是7分鐘,你可以直接設置為0
                        RequireExpirationTime = true,
                    };
                });
            #endregion

(2).Configure啟用

app.UseAuthentication();//jwt

四、創建jwt幫助類

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>
            /// 配置屬性
            /// </summary>
            public IConfiguration Configuration { get; }
            /// <summary>
            /// 生成Token
            /// </summary>
            /// <returns></returns>
            public string GenerateToken(List<Claim> claims)
            {
                var jwtConfig = Configuration.GetSection("Jwt");
                //秘鑰,就是標頭,這裡用Hmacsha256算法,需要256bit的密鑰
                var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.GetValue<string>("Secret"))), SecurityAlgorithms.HmacSha256);
                //Claim,JwtRegisteredClaimNames中預定義瞭好多種默認的參數名,也可以像下面的Guid一樣自己定義鍵名.
                //ClaimTypes也預定義瞭好多類型如role、email、name。Role用於賦予權限,不同的角色可以訪問不同的接口
                //相當於有效載荷
                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>();//合並Claim,刪除重復項目
 
                SecurityToken securityToken = new JwtSecurityToken(
                    signingCredentials: securityKey,
                    expires: DateTime.Now.AddDays(1),//過期時間
                    claims: claims
                );
                //生成jwt令牌
                return new JwtSecurityTokenHandler().WriteToken(securityToken);
            }
        }
    }

五、測試登錄成功把賬戶信息存進token

 /// 登錄
        /// </summary>
        /// <returns>登錄</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();
        }

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: