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

.NET core 3.0如何使用Jwt保護(hù)api詳解

 更新時間:2019年11月25日 15:17:43   作者:成天  
這篇文章主要給大家介紹了關(guān)于.NET core 3.0如何使用Jwt保護(hù)api的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用.NET core 3.0具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

摘要:

本文演示如何向有效用戶提供jwt,以及如何在webapi中使用該token通過JwtBearerMiddleware中間件對用戶進(jìn)行身份認(rèn)證。

認(rèn)證和授權(quán)區(qū)別?

首先我們要弄清楚認(rèn)證(Authentication)和授權(quán)(Authorization)的區(qū)別,以免混淆了。認(rèn)證是確認(rèn)的過程中你是誰,而授權(quán)圍繞是你被允許做什么,即權(quán)限。顯然,在確認(rèn)允許用戶做什么之前,你需要知道他們是誰,因此,在需要授權(quán)時,還必須以某種方式對用戶進(jìn)行身份驗證。

什么是JWT?

根據(jù)維基百科的定義,JSON WEB Token(JWT),是一種基于JSON的、用于在網(wǎng)絡(luò)上聲明某種主張的令牌(token)。JWT通常由三部分組成:頭信息(header),消息體(payload)和簽名(signature)。

頭信息指定了該JWT使用的簽名算法:

header = '{"alg":"HS256","typ":"JWT"}'

HS256表示使用了HMAC-SHA256來生成簽名。

消息體包含了JWT的意圖:

payload = '{"loggedInAs":"admin","iat":1422779638}'//iat表示令牌生成的時間

未簽名的令牌由base64url編碼的頭信息和消息體拼接而成(使用"."分隔),簽名則通過私有的key計算而成:

key = 'secretkey' 
unsignedToken = encodeBase64(header) + '.' + encodeBase64(payload) 
signature = HMAC-SHA256(key, unsignedToken)

最后在未簽名的令牌尾部拼接上base64url編碼的簽名(同樣使用"."分隔)就是JWT了:

token = encodeBase64(header) + '.' + encodeBase64(payload) + '.' + encodeBase64(signature)

# token看起來像這樣: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI

JWT常常被用作保護(hù)服務(wù)端的資源(resource),客戶端通常將JWT通過HTTP的Authorization header發(fā)送給服務(wù)端,服務(wù)端使用自己保存的key計算、驗證簽名以判斷該JWT是否可信:

Authorization: Bearer eyJhbGci*...<snip>...*yu5CSpyHI

準(zhǔn)備工作

使用vs2019創(chuàng)建webapi項目,并且安裝nuget包

Microsoft.AspNetCore.Authentication.JwtBearer


Startup類

ConfigureServices 添加認(rèn)證服務(wù)

services.AddAuthentication(options =>
   {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
   }).AddJwtBearer(options =>
   {
    options.SaveToken = true;
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
     ValidateIssuer = true,
     ValidateAudience = true,
     ValidAudience = "https://www.cnblogs.com/chengtian",
     ValidIssuer = "https://www.cnblogs.com/chengtian",
     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey"))
    };
   });

Configure 配置認(rèn)證中間件

 app.UseAuthentication();//認(rèn)證中間件、

創(chuàng)建一個token

添加一個登錄model命名為LoginInput

public class LoginInput
 {

  public string Username { get; set; }

  public string Password { get; set; }
 }

添加一個認(rèn)證控制器命名為AuthenticateController

[Route("api/[controller]")]
 public class AuthenticateController : Controller
 {
  [HttpPost]
  [Route("login")]
  public IActionResult Login([FromBody]LoginInput input)
  {
   //從數(shù)據(jù)庫驗證用戶名,密碼 
   //驗證通過 否則 返回Unauthorized

   //創(chuàng)建claim
   var authClaims = new[] {
    new Claim(JwtRegisteredClaimNames.Sub,input.Username),
    new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
   };
   IdentityModelEventSource.ShowPII = true;
   //簽名秘鑰 可以放到j(luò)son文件中
   var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey"));

   var token = new JwtSecurityToken(
     issuer: "https://www.cnblogs.com/chengtian",
     audience: "https://www.cnblogs.com/chengtian",
     expires: DateTime.Now.AddHours(2),
     claims: authClaims,
     signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
     );

   //返回token和過期時間
   return Ok(new
   {
    token = new JwtSecurityTokenHandler().WriteToken(token),
    expiration = token.ValidTo
   });
  }
 }

添加api資源

利用默認(rèn)的控制器WeatherForecastController

  • 添加個Authorize標(biāo)簽
  • 路由調(diào)整為:[Route("api/[controller]")] 代碼如下
 [Authorize]
 [ApiController]
 [Route("api/[controller]")]
 public class WeatherForecastController : ControllerBase

到此所有的代碼都已經(jīng)準(zhǔn)好了,下面進(jìn)行運行測試

運行項目

使用postman進(jìn)行模擬

輸入url:https://localhost:44364/api/weatherforecast

    

發(fā)現(xiàn)返回時401未認(rèn)證,下面獲取token

通過用戶和密碼獲取token

如果我們的憑證正確,將會返回一個token和過期日期,然后利用該令牌進(jìn)行訪問

利用token進(jìn)行請求

ok,最后發(fā)現(xiàn)請求狀態(tài)200!

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論