欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET Core學(xué)習(xí)之使用JWT認證授權(quán)詳解

 更新時間:2020年08月16日 11:24:53   作者:WilsonPan  
這篇文章主要給大家介紹了關(guān)于ASP.NET Core學(xué)習(xí)之使用JWT認證授權(quán)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用ASP.NET Core具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

概述

認證授權(quán)是很多系統(tǒng)的基本功能 , 在以前PC的時代 , 通常是基于cookies-session這樣的方式實現(xiàn)認證授權(quán) , 在那個時候通常系統(tǒng)的用戶量都不會很大, 所以這種方式也一直很好運行, 隨著現(xiàn)在都軟件用戶量越來越大, 系統(tǒng)架構(gòu)也從以前垂直擴展(增加服務(wù)器性能) -> 水平擴展(增加服務(wù)器數(shù)量)

cookies-session 工作方式

客戶端提交用戶信息 -> 服務(wù)器識別用戶 -> 服務(wù)端保存用戶信息 -> 返回session-id客戶端 -> 客戶端保存session-id -> 每次請求cookies帶上session-id

這種方式也不是不能水平擴展 , 例如 , session復(fù)制/第三方保存session(數(shù)據(jù)庫 , Redis)

名詞解析

認證 : 識別用戶是否合法

授權(quán): 賦予用戶權(quán)限 (能訪問哪些資源)

鑒權(quán): 鑒定權(quán)限是否合法

Jwt優(yōu)勢與劣勢

優(yōu)勢

無狀態(tài)

token 存儲身份驗證所有信息 , 服務(wù)端不需要保存用戶身份驗證信息, 減少服務(wù)端壓力 , 服務(wù)端更容易水平擴展, 由于無狀態(tài), 又會導(dǎo)致它最大缺點 , 很難注銷

2、支持跨域訪問

Cookie是不允許垮域訪問的,token支持

3、跨語言

基于標準化的 JSON Web Token (JWT) , 不依賴特定某一個語言 , 例如生成對Token可以對多個語言使用(Net , Java , PHP ...)

劣勢

1、Token有效性問題

后臺很難注銷已經(jīng)發(fā)布的Token , 通常需要借助第三方儲存(數(shù)據(jù)庫/緩存) 實現(xiàn)注銷, 這樣就會失去JWT最大的優(yōu)勢

2、占帶寬

Token長度(取決存放內(nèi)容) 比session_id大 , 每次請求多消耗帶寬 , token只存必要信息 , 避免token過長

3、需要實現(xiàn)續(xù)簽

cookies - session 通常是框架已經(jīng)實現(xiàn)續(xù)簽功能, 每次訪問把過期時間更新, JWT需要自己實現(xiàn), 參考OAuth2刷新Token機制實現(xiàn)刷新Token

4、消耗更多CPU

每次請求需要對內(nèi)容解密和驗證簽名這兩步操作,典型用時間換空間

只能根據(jù)自身使用場景決定使用哪一種身份驗證方案 , 沒有一種方案是通用的,完美的

AspNetCore集成Jwt認證

1、添加包

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

2、添加配置

"JwtOptions": {
 "Issuer": "https://localhost:5001",
 "Audience": "https://localhost:5001",
 "SecurityKey": "1G3l0yYGbOINId3A*ioEi4iyxR7$SPzm"
}

3、Jwt Bearer 擴展(選項)

public static AuthenticationBuilder AddJwtBearer(this IServiceCollection services, Action<JwtOptions> configureOptions)
{
 if (configureOptions == null) throw new ArgumentNullException(nameof(configureOptions));

 var jwtOptions = new JwtOptions()
 {
  Issuer = "Jwt Authentication",
  Audience = "Wilson Pan Web Api",
 };
 // set customs optoins
 configureOptions(jwtOptions);

 // update Options 
 services.PostConfigure<JwtOptions>(options =>
 {
  options.Issuer = jwtOptions.Issuer;
  options.Audience = jwtOptions.Audience;
  options.SecurityKey = jwtOptions.SecurityKey;
 });

 return services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
      options.TokenValidationParameters = new TokenValidationParameters()
      {
       ValidIssuer = jwtOptions.Issuer,
       ValidAudience = jwtOptions.Audience,
       ValidateIssuer = true,
       ValidateLifetime = true,
       ValidateIssuerSigningKey = true,
       IssuerSigningKey = jwtOptions.SymmetricSecurityKey
      };
     });

}

4、ConfigureServices

services.AddJwtBearer(options =>
{
 options.Issuer = Configuration.GetValue<string>("JwtOptions:Issuer");
 options.Audience = Configuration.GetValue<string>("JwtOptions:Audience");
 options.SecurityKey = Configuration.GetValue<string>("JwtOptions:SecurityKey");
});

5、Configure

app.UseAuthentication();
app.UseAuthorization();

6、add AuthorizeController

//define claim 
var claims = new Claim[]
{
  new Claim(ClaimTypes.Name, username),
  new Claim(ClaimTypes.Email, $"{username}@github.com"),
  new Claim(ClaimTypes.Role, username == "WilsonPan" ? "Admin" : "Reader"),
  new Claim(ClaimTypes.Hash, JwtHashHelper.GetHashString($"{username}:{password}:{System.DateTime.Now.Ticks}")),
};

//define JwtSecurityToken
var token = new JwtSecurityToken(
  issuer: _jwtOptions.Issuer,
  audience: _jwtOptions.Audience,
  claims: claims,
  expires: System.DateTime.Now.AddMinutes(5),
  signingCredentials: _jwtOptions.SigningCredentials
);

// generate token
var result = new JwtSecurityTokenHandler().WriteToken(token);

7、Contrller/Action 添加認證授權(quán)

[ApiController]
[Authorize]
[Route("[controller]")]
public class ApiController : ControllerBase
{
  ...
}

[HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult Post()
{
  return Ok();
}

Rest Client

dotnet run

1、認證接口

@host = https://localhost:5001

# @name token
POST {{host}}/Authorize HTTP/1.1
Content-Type: application/x-www-form-urlencoded

#username=Wilson&password=123456
# admin 
username=WilsonPan&password=123456

2、需要授權(quán)接口

### required authorize
GET {{host}}/api HTTP/1.1
Authorization: Bearer {{token.response.body.*}}

3、需要管理員角色接口

### required authorize
POST {{host}}/api HTTP/1.1
Authorization: Bearer {{token.response.body.*}}

示例代碼

總結(jié)

到此這篇關(guān)于ASP.NET Core學(xué)習(xí)之使用JWT認證授權(quán)的文章就介紹到這了,更多相關(guān)ASP.NET Core用JWT認證授權(quán)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論