ASP.NET Core WebAPI中使用JWT Bearer認證和授權


ASP.NET Core WebAPI中使用JWT Bearer認證和授權

 

1. 什么是JWT?

        JWT是一種用於雙方之間傳遞安全信息的簡潔的、URL安全的表述性聲明規范。JWT作為一個開放的標准(RFC 7519),定義了一種簡潔的,自包含的方法用於通信雙方之間以Json對象的形式安全的傳遞信息。因為數字簽名的存在,這些信息是可信的,JWT可以使用HMAC算法或者是RSA的公私秘鑰對進行簽名。簡潔(Compact): 可以通過URL,POST參數或者在HTTP header發送,因為數據量小,傳輸速度也很快 自包含(Self-contained):負載中包含了所有用戶所需要的信息,避免了多次查詢數據庫。

2. JWT 的應用場景是什么?

       身份認證在這種場景下,一旦用戶完成了登陸,在接下來的每個請求中包含JWT,可以用來驗證用戶身份以及對路由,服務和資源的訪問權限進行驗證。由於它的開銷非常小,可以輕松的在不同域名的系統中傳遞,所有目前在單點登錄(SSO)中比較廣泛的使用了該技術。 信息交換在通信的雙方之間使用JWT對數據進行編碼是一種非常安全的方式,由於它的信息是經過簽名的,可以確保發送者發送的信息是沒有經過偽造的

3. JWT的結構 

JWT包含了使用.分隔的三部分: Header 頭部 Payload 負載 Signature 簽名

其結構看起來是這樣的Header.Payload.Signature

Header

在header中通常包含了兩部分:token類型和采用的加密算法。{ "alg": "HS256", "typ": "JWT"} 接下來對這部分內容使用 Base64Url 編碼組成了JWT結構的第一部分。

Payload

  Token的第二部分是負載,它包含了claim, Claim是一些實體(通常指的用戶)的狀態和額外的元數據,有三種類型的claim:reservedpublic 和 private.Reserved claims: 這些claim是JWT預先定義的,在JWT中並不會強制使用它們,而是推薦使用,常用的有 iss(簽發者),exp(過期時間戳), sub(面向的用戶), aud(接收方), iat(簽發時間)。 Public claims:根據需要定義自己的字段,注意應該避免沖突 Private claims:這些是自定義的字段,可以用來在雙方之間交換信息 負載使用的例子:{ "sub": "1234567890", "name": "John Doe", "admin": true} 上述的負載需要經過Base64Url編碼后作為JWT結構的第二部分。

Signature

  創建簽名需要使用編碼后的header和payload以及一個秘鑰,使用header中指定簽名算法進行簽名。例如如果希望使用HMAC SHA256算法,那么簽名應該使用下列方式創建: HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) 簽名用於驗證消息的發送者以及消息是沒有經過篡改的。 完整的JWT 完整的JWT格式的輸出是以. 分隔的三段Base64編碼,與SAML等基於XML的標准相比,JWT在HTTP和HTML環境中更容易傳遞。 下列的JWT展示了一個完整的JWT格式,它拼接了之前的Header, Payload以及秘鑰簽名:

4. 如何使用JWT?

  在身份鑒定的實現中,傳統方法是在服務端存儲一個session,給客戶端返回一個cookie,而使用JWT之后,當用戶使用它的認證信息登陸系統之后,會返回給用戶一個JWT,用戶只需要本地保存該token(通常使用local storage,也可以使用cookie)即可。 當用戶希望訪問一個受保護的路由或者資源的時候,通常應該在Authorization頭部使用Bearer模式添加JWT,其內容看起來是下面這樣:Authorization: Bearer <token>

因為用戶的狀態在服務端的內存中是不存儲的,所以這是一種無狀態的認證機制。服務端的保護路由將會檢查請求頭Authorization中的JWT信息,如果合法,則允許用戶的行為。由於JWT是自包含的,因此減少了需要查詢數據庫的需要。 JWT的這些特性使得我們可以完全依賴其無狀態的特性提供數據API服務,甚至是創建一個下載流服務。因為JWT並不使用Cookie的,所以你可以使用任何域名提供你的API服務而不需要擔心跨域資源共享問題(CORS)。 下面的序列圖展示了該過程:

5. 為什么要使用JWT?

  相比XML格式,JSON更加簡潔,編碼之后更小,這使得JWT比SAML更加簡潔,更加適合在HTML和HTTP環境中傳遞。 在安全性方面,SWT只能夠使用HMAC算法和共享的對稱秘鑰進行簽名,而JWT和SAML token則可以使用X.509認證的公私秘鑰對進行簽名。與簡單的JSON相比,XML和XML數字簽名會引入復雜的安全漏洞。 因為JSON可以直接映射為對象,在大多數編程語言中都提供了JSON解析器,而XML則沒有這么自然的文檔-對象映射關系,這就使得使用JWT比SAML更方便

6. 在ASP.NET Core WebAPI 中應用

      安裝JWT依賴包

 

接下來我們需要新建一個文件夾Models,在文件夾下面新建一個類JwtSettings.cs

復制代碼
public class JwtSetting
    {
        /// <summary>
        /// 頒發者
        /// </summary>
        public string Issuer { get; set; }

        /// <summary>
        /// 接收者
        /// </summary>
        public string Audience { get; set; }

        /// <summary>
        /// 令牌密碼
        /// </summary>
        public string SecurityKey { get; set; }

        /// <summary>
        ///  過期時間
        /// </summary>
        public long ExpireSeconds { get; set; }

        /// <summary>
        /// 簽名
        /// </summary>
        public SigningCredentials Credentials
        {
            get
            {
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey));
                return new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            }
        }
    }
復制代碼

 

 

 

 

 然后我們需要在appsettings.json中配置jwt參數的值 【注意】 SecretKey必須大於16個,是大於,不是大於等於

復制代碼
  {
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*","JwtSetting": {
      "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB", // 密鑰
      "Issuer": "http://localhost:5000", // 頒發者
      "Audience": "http://localhost:5000" // 接收者
    }
}
復制代碼

 

 

  

Startup注入服務( app.UseAuthentication();需要放在app.UseMvc();前面 )

復制代碼
public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<FormOptions>(x => x.MultipartBodyLengthLimit = 1073741822);

            services.AddMvc(opt =>
            {
                opt.Filters.Add(new ProducesAttribute("application/json"));
            });

            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });

            services.Configure<JwtSetting>(Configuration.GetSection("JwtSetting"));
            //HttpResponseMessage結構
            services.AddMvc().AddWebApiConventions();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddMvcCore().AddApiExplorer();

            //services.AddMvc().AddJsonOptions(options =>
            //{
            //    處理返回結構屬性首字母不被小寫
            //     對 JSON 數據使用混合大小寫。跟屬性名同樣的大小.輸出
            //    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            //});
            services.AddCors(options => options.AddPolicy("CorsSample", p =>
               p.WithOrigins("*")
               .AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials()
            ));
            #region Jwt
            var jwtSetting = new JwtSetting();
            Configuration.Bind("JwtSetting", jwtSetting);
            //添加策略鑒權模式
            services.AddAuthorization()
               .AddAuthentication(x =>
               {
                   x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                   x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                   x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
               })
               .AddJwtBearer(option =>
               {
                   option.TokenValidationParameters = new TokenValidationParameters
                   {
                       ValidateLifetime = true,//是否驗證失效時間
                       ClockSkew = TimeSpan.FromSeconds(30),

                       ValidateAudience = true,//是否驗證Audience
                                               //ValidAudience = Const.GetValidudience(),//Audience
                                               //這里采用動態驗證的方式,在重新登陸時,刷新token,舊token就強制失效了
                       AudienceValidator = (m, n, z) =>
                       {
                           return m != null && m.FirstOrDefault().Equals(jwtSetting.Audience);
                       },
                       ValidateIssuer = true,//是否驗證Issuer
                       ValidIssuer = jwtSetting.Issuer,//Issuer,這兩項和前面簽發jwt的設置一致

                       ValidateIssuerSigningKey = true,//是否驗證SecurityKey
                       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.SecurityKey))//拿到SecurityKey
                   };
               });
            #endregion
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseStaticFiles(new StaticFileOptions
            {
                ServeUnknownFileTypes = true
            });
            //配置Cors
            app.UseCors("CorsSample");
            //app.UseHttpsRedirection();
            app.UseMvc();
        }
復制代碼

新建用戶實體類

復制代碼
public class UserEntity
    {
        /// <summary>
        /// ID
        /// </summary>
        public int id { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string username { get; set; }
        /// <summary>
        /// 密碼
        /// </summary>
        public string password { get; set; }

    }
復制代碼

接下來在Controllers文件夾下新建控制器AuthController.cs,進行編寫獲取Token的接口,完整代碼如下

復制代碼
/// <summary>
    /// 權限(獲取Token)
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class AuthController : ApiController
    {
        private readonly ITokenService _tokenService;
        /// <summary>
        /// 
        /// </summary>
        public AuthController(ITokenService tokenService)
        {
            _tokenService = tokenService;
        }
        /// <summary>
        /// 獲取Token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public MethodResult GetToken(UserEntity user)
        {
            var token = _tokenService.GetToken(user);
            var response = new
            {
                Status = true,
                Token = token,
                Type = "Bearer"
            };
            return new MethodResult(response);
        }
    }
復制代碼
復制代碼
public class TokenService : ITokenService
    {
        private readonly JwtSetting _jwtSetting;
        public TokenService(IOptions<JwtSetting> option)
        {
            _jwtSetting = option.Value;
        }

        public string GetToken(UserEntity user)
        {
            //創建用戶身份標識,這里可以隨意加入自定義的參數,key可以自己隨便起
            var claims = new[]
            {
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
                    new Claim(ClaimTypes.NameIdentifier, user.username.ToString()),
                    new Claim("Id", user.id.ToString()),
                    new Claim("Name", user.username.ToString())
                };
            //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSetting.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
            var token = new JwtSecurityToken(
                //頒發者
                issuer: _jwtSetting.Issuer,
                //接收者
                audience: _jwtSetting.Audience,
                //過期時間
                expires: DateTime.Now.AddMinutes(30),
                //簽名證書
                signingCredentials: creds,
                //自定義參數
                claims: claims
                );
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return jwtToken;
        }
    }
復制代碼

接下來就開始做驗證!

PostMan測試獲取token

 

接下來做權限校驗

在需要授權的api上新增 [Authorize] 標記

復制代碼
    /// <summary>
    /// 博客
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BlogController : ControllerBase
    {
        private readonly IBlogService _blogService;
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="blogService"></param>
        public BlogController(IBlogService blogService)
        {
            _blogService = blogService;
        }
        /// <summary>
        /// 獲取博客列表
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public MethodResult GetAllBlogs(int? id = null)
        {
            var userId = this.CurUserID();
            return new MethodResult(_blogService.GetAllBlogs(id));
        }
    }
復制代碼

 

封裝獲取token自定義信息

復制代碼
public static class CurUser
    {
        /// <summary>
        /// 獲取當前登錄用戶的用戶編號
        /// </summary>
        public static int CurUserID(this ControllerBase controller)
        {
            var auth = controller.HttpContext.AuthenticateAsync().Result.Principal.Claims;
            var userId = auth.FirstOrDefault(t => t.Type.Equals("Id"))?.Value;

            return userId == null ? 0 : Convert.ToInt32(userId);
        }

        /// <summary>
        /// 獲取當前登錄用戶的姓名
        /// </summary>
        public static string CurUserName(this ControllerBase controller)
        {
            var auth = controller.HttpContext.AuthenticateAsync().Result.Principal.Claims;
            var userName = auth.FirstOrDefault(t => t.Type.Equals("Name"))?.Value;

            return userName == null ? "" : userName;
        }
    }
復制代碼

接下來進行PostMan測試

 

 

jwt token解析:https://jwt.io/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM