内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

怎么在ASP.NetCore3.0項(xiàng)目中使用JWT認(rèn)證-創(chuàng)新互聯(lián)

怎么在ASP.Net Core3.0項(xiàng)目中使用JWT認(rèn)證?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

目前創(chuàng)新互聯(lián)已為成百上千的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)絡(luò)空間、網(wǎng)站托管維護(hù)、企業(yè)網(wǎng)站設(shè)計(jì)、雙清網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。

JWT主要由三部分組成,如下:


HEADER.PAYLOAD.SIGNATURE

HEADER 包含token的元數(shù)據(jù),主要是加密算法,和簽名的類型,如下面的信息,說(shuō)明了

加密的對(duì)象類型是JWT,加密算法是HMAC SHA-256

{"alg":"HS256","typ":"JWT"}

然后需要通過(guò)BASE64編碼后存入token中

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Payload 主要包含一些聲明信息(claim),這些聲明是key-value對(duì)的數(shù)據(jù)結(jié)構(gòu)。

通常如用戶名,角色等信息,過(guò)期日期等,因?yàn)槭俏醇用艿?,所以不建議存放敏感信息。

{"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name":"admin","exp":1578645536,"iss":"webapi.cn","aud":"WebApi"}

也需要通過(guò)BASE64編碼后存入token中

eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDU1MzYsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9

Signature jwt要符合jws(Json Web Signature)的標(biāo)準(zhǔn)生成一個(gè)最終的簽名。把編碼后的Header和Payload信息加在一起,然后使用一個(gè)強(qiáng)加密算法,如 HmacSHA256,進(jìn)行加密。HS256(BASE64(Header).Base64(Payload),secret)

2_akEH40LR2QWekgjm8Tt3lesSbKtDethmJMo_3jpF4

最后生成的token如下

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDU1MzYsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9.2_akEH40LR2QWekgjm8Tt3lesSbKtDethmJMo_3jpF4

開發(fā)環(huán)境

框架:asp.net 3.1

IDE:VS2019

ASP.NET 3.1 Webapi中使用JWT認(rèn)證

命令行中執(zhí)行執(zhí)行以下命令,創(chuàng)建webapix項(xiàng)目:

dotnet new webapi -n Webapi -o WebApi

特別注意的時(shí),3.x默認(rèn)是沒(méi)有jwt的Microsoft.AspNetCore.Authentication.JwtBearer庫(kù)的,所以需要手動(dòng)添加NuGet Package,切換到項(xiàng)目所在目錄,執(zhí)行 .net cli命令

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 3.1.0

創(chuàng)建一個(gè)簡(jiǎn)單的POCO類,用來(lái)存儲(chǔ)簽發(fā)或者驗(yàn)證jwt時(shí)用到的信息

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Webapi.Models

{
  public class TokenManagement
  {
    [JsonProperty("secret")]
    public string Secret { get; set; }

    [JsonProperty("issuer")]
    public string Issuer { get; set; }

    [JsonProperty("audience")]
    public string Audience { get; set; }

    [JsonProperty("accessExpiration")]
    public int AccessExpiration { get; set; }

    [JsonProperty("refreshExpiration")]
    public int RefreshExpiration { get; set; }
  }
}

然后在appsettings.Development.json 增加jwt使用到的配置信息(如果是生成環(huán)境在appsettings.json 添加即可)

"tokenManagement": {
    "secret": "123456",
    "issuer": "webapi.cn",
    "audience": "WebApi",
    "accessExpiration": 30,
    "refreshExpiration": 60
  }

然后再startup類的ConfigureServices方法中增加讀取配置信息

public void ConfigureServices(IServiceCollection services)
    {
      services.AddControllers();
      services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
      var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();

    }

到目前為止,我們完成了一些基礎(chǔ)工作,下面再webapi中注入jwt的驗(yàn)證服務(wù),并在中間件管道中啟用authentication中間件。

startup類中要引用jwt驗(yàn)證服務(wù)的命名空間

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

然后在ConfigureServices 方法中添加如下邏輯

services.AddAuthentication(x =>
      {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
      }).AddJwtBearer(x =>
      {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters
        {
          ValidateIssuerSigningKey = true,
          IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
          ValidIssuer = token.Issuer,
          ValidAudience = token.Audience,
          ValidateIssuer = false,
          ValidateAudience = false
        };
      });

Configure 方法中啟用驗(yàn)證

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseHttpsRedirection();

      app.UseAuthentication();
      app.UseRouting();

      app.UseAuthorization();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers();
      });
    }

上面完成了JWT驗(yàn)證的功能,下面就需要增加簽發(fā)token的邏輯。我們需要增加一個(gè)專門用來(lái)用戶認(rèn)證和簽發(fā)token的控制器,命名成AuthenticationController ,同時(shí)增加一個(gè)請(qǐng)求的DTO類

public class LoginRequestDTO
  {
    [Required]
    [JsonProperty("username")]
    public string Username { get; set; }


    [Required]
    [JsonProperty("password")]
    public string Password { get; set; }
  }
[Route("api/[controller]")]
  [ApiController]
  public class AuthenticationController : ControllerBase
  {
    [AllowAnonymous]
     [HttpPost, Route("requestToken")]
    public ActionResult RequestToken([FromBody] LoginRequestDTO request)
    {
      if (!ModelState.IsValid)
      {
        return BadRequest("Invalid Request");
      }

      return Ok();

    }
  }

目前上面的控制器只實(shí)現(xiàn)了基本的邏輯,下面我們要?jiǎng)?chuàng)建簽發(fā)token的服務(wù),去完成具體的業(yè)務(wù)。第一步我們先創(chuàng)建對(duì)應(yīng)的服務(wù)接口,命名為IAuthenticateService

public interface IAuthenticateService
  {
    bool IsAuthenticated(LoginRequestDTO request, out string token);
  }

接下來(lái),實(shí)現(xiàn)接口

public class TokenAuthenticationService : IAuthenticateService
  {
    public bool IsAuthenticated(LoginRequestDTO request, out string token)
    {
      throw new NotImplementedException();
    }
  }

StartupConfigureServices 方法中注冊(cè)服務(wù)

services.AddScoped<IAuthenticateService, TokenAuthenticationService>();

在Controller中注入IAuthenticateService服務(wù),并完善action

public class AuthenticationController : ControllerBase
  {
    private readonly IAuthenticateService _authService;
    public AuthenticationController(IAuthenticateService authService)
    {
      this._authService = authService;
    }
    [AllowAnonymous]
     [HttpPost, Route("requestToken")]
    public ActionResult RequestToken([FromBody] LoginRequestDTO request)
    {
      if (!ModelState.IsValid)
      {
        return BadRequest("Invalid Request");
      }

      string token;
      if (_authService.IsAuthenticated(request, out token))
      {
        return Ok(token);
      }

      return BadRequest("Invalid Request");

    }
  }

正常情況,我們都會(huì)根據(jù)請(qǐng)求的用戶和密碼去驗(yàn)證用戶是否合法,需要連接到數(shù)據(jù)庫(kù)獲取數(shù)據(jù)進(jìn)行校驗(yàn),我們這里為了方便,假設(shè)任何請(qǐng)求的用戶都是合法的。

這里單獨(dú)加個(gè)用戶管理的服務(wù),不在IAuthenticateService這個(gè)服務(wù)里面添加相應(yīng)邏輯,主要遵循了職責(zé)單一原則 。首先和上面一樣,創(chuàng)建一個(gè)服務(wù)接口IUserService

public interface IUserService
  {
    bool IsValid(LoginRequestDTO req);
  }

實(shí)現(xiàn)IUserService 接口

public class UserService : IUserService
  {
    //模擬測(cè)試,默認(rèn)都是人為驗(yàn)證有效
    public bool IsValid(LoginRequestDTO req)
    {
      return true;
    }
  }

同樣注冊(cè)到容器中

services.AddScoped<IUserService, UserService>();

接下來(lái),就要完善TokenAuthenticationService簽發(fā)token的邏輯,首先要注入IUserService 和 TokenManagement,然后實(shí)現(xiàn)具體的業(yè)務(wù)邏輯,這個(gè)token的生成還是使用的Jwt的類庫(kù)提供的api,具體不詳細(xì)描述。

特別注意下TokenManagement的注入是已IOptions的接口類型注入的,還記得在Startpup中嗎?我們是通過(guò)配置項(xiàng)的方式注冊(cè)TokenManagement類型的。

public class TokenAuthenticationService : IAuthenticateService
  {
    private readonly IUserService _userService;
    private readonly TokenManagement _tokenManagement;
    public TokenAuthenticationService(IUserService userService, IOptions<TokenManagement> tokenManagement)
    {
      _userService = userService;
      _tokenManagement = tokenManagement.Value;
    }
    public bool IsAuthenticated(LoginRequestDTO request, out string token)
    {
      token = string.Empty;
      if (!_userService.IsValid(request))
        return false;
      var claims = new[]
      {
        new Claim(ClaimTypes.Name,request.Username)
      };
      var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
      var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
      var jwtToken = new JwtSecurityToken(_tokenManagement.Issuer, _tokenManagement.Audience, claims, expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration), signingCredentials: credentials);

      token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

      return true;

    }
  }

準(zhǔn)備好測(cè)試試用的APi,打上Authorize特性,表明需要授權(quán)!

[ApiController]
  [Route("[controller]")]
  [Authorize]
  public class WeatherForecastController : ControllerBase
  {
    private static readonly string[] Summaries = new[]
    {
      "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
      _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
      var rng = new Random();
      return Enumerable.Range(1, 5).Select(index => new WeatherForecast
      {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
      })
      .ToArray();
    }
  }

支持我們可以測(cè)試驗(yàn)證了,我們可以使用postman來(lái)進(jìn)行http請(qǐng)求,先啟動(dòng)http服務(wù),獲取url,先測(cè)試一個(gè)訪問(wèn)需要授權(quán)的接口,但沒(méi)有攜帶token信息,返回是401,表示未授權(quán)

怎么在ASP.Net Core3.0項(xiàng)目中使用JWT認(rèn)證

下面我們先通過(guò)認(rèn)證接口,獲取token,居然報(bào)錯(cuò),查詢了下,發(fā)現(xiàn)HS256算法的秘鑰長(zhǎng)度新為128位,轉(zhuǎn)換成字符至少16字符,之前設(shè)置的秘鑰是123456,所以導(dǎo)致異常。

System.ArgumentOutOfRangeException: IDX10603: Decryption failed. Keys tried: 'HS256'. Exceptions caught: '128'. token: '48' (Parameter 'KeySize') at

更新秘鑰

 "tokenManagement": {
    "secret": "123456123456123456",
    "issuer": "webapi.cn",
    "audience": "WebApi",
    "accessExpiration": 30,
    "refreshExpiration": 60
  }

重新發(fā)起請(qǐng)求,成功獲取token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDUyMDMsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9.AehD8WTAnEtklof2OJsvg0U4_o8_SjdxmwUjzAiuI-o

怎么在ASP.Net Core3.0項(xiàng)目中使用JWT認(rèn)證

把token帶到之前請(qǐng)求的api中,重新測(cè)試,成功獲取數(shù)據(jù)

怎么在ASP.Net Core3.0項(xiàng)目中使用JWT認(rèn)證

關(guān)于怎么在ASP.Net Core3.0項(xiàng)目中使用JWT認(rèn)證問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

名稱欄目:怎么在ASP.NetCore3.0項(xiàng)目中使用JWT認(rèn)證-創(chuàng)新互聯(lián)
鏈接地址:http://www.rwnh.cn/article10/csdigo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、網(wǎng)站設(shè)計(jì)品牌網(wǎng)站建設(shè)、外貿(mào)建站、品牌網(wǎng)站制作關(guān)鍵詞優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)
鹿泉市| 赤水市| 东兰县| 兴城市| 浦县| 建宁县| 临湘市| 威海市| 酒泉市| 双辽市| 景德镇市| 克东县| 丰原市| 昭通市| 隆化县| 新兴县| 满城县| 揭阳市| 绥阳县| 冷水江市| 博爱县| 成武县| 大名县| 上虞市| 平顶山市| 兴仁县| 宁都县| 曲靖市| 沅陵县| 阿勒泰市| 湖南省| 阿拉善左旗| 合作市| 滁州市| 凭祥市| 尖扎县| 诸城市| 来宾市| 南丰县| 宁武县| 富源县|