ASP.Net Core 3.1 中使用JWT認證

JWT認證簡單介紹

    關於Jwt的介紹網上不少,此處不在贅述,咱們主要看看jwt的結構。web

    JWT主要由三部分組成,以下:算法

HEADER.PAYLOAD.SIGNATURE

    HEADER包含token的元數據,主要是加密算法,和簽名的類型,以下面的信息,說明了shell

加密的對象類型是JWT,加密算法是HMAC SHA-256數據庫

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

    而後須要經過BASE64編碼後存入token中json

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9    

    Payload主要包含一些聲明信息(claim),這些聲明是key-value對的數據結構。api

一般如用戶名,角色等信息,過時日期等,由於是未加密的,因此不建議存放敏感信息。安全

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

也須要經過BASE64編碼後存入token中cookie

eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDU1MzYsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9

     Signaturejwt要符合jws(Json Web Signature)的標準生成一個最終的簽名。把編碼後的Header和Payload信息加在一塊兒,而後使用一個強加密算法,如 HmacSHA256,進行加密。HS256(BASE64(Header).Base64(Payload),secret)數據結構

2_akEH40LR2QWekgjm8Tt3lesSbKtDethmJMo_3jpF4

    最後生成的token以下app

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDU1MzYsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9.2_akEH40LR2QWekgjm8Tt3lesSbKtDethmJMo_3jpF4

   

開發環境

框架:asp.net 3.1

IDE:VS2019

ASP.NET 3.1 Webapi中使用JWT認證

    命令行中執行執行如下命令,建立webapix項目:

dotnet new webapi -n Webapi -o WebApi

    特別注意的時,3.x默認是沒有jwt的Microsoft.AspNetCore.Authentication.JwtBearer庫的,因此須要手動添加NuGet Package,切換到項目所在目錄,執行 .net cli命令

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

    建立一個簡單的POCO類,用來存儲簽發或者驗證jwt時用到的信息

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使用到的配置信息(若是是生成環境在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>();

        }

    到目前爲止,咱們完成了一些基礎工做,下面再webapi中注入jwt的驗證服務,並在中間件管道中啓用authentication中間件。

    startup類中要引用jwt驗證服務的命名空間

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方法中啓用驗證

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驗證的功能,下面就須要增長簽發token的邏輯。咱們須要增長一個專門用來用戶認證和簽發token的控制器,命名成AuthenticationController,同時增長一個請求的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();

        }
    }

    目前上面的控制器只實現了基本的邏輯,下面咱們要建立簽發token的服務,去完成具體的業務。第一步咱們先建立對應的服務接口,命名爲IAuthenticateService

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

    接下來,實現接口

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

    在StartupConfigureServices方法中註冊服務

services.AddScoped<IAuthenticateService, TokenAuthenticationService>();

    在Controller中注入IAuthenticateService服務,並完善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");

        }
    }

    正常狀況,咱們都會根據請求的用戶和密碼去驗證用戶是否合法,須要鏈接到數據庫獲取數據進行校驗,咱們這裏爲了方便,假設任何請求的用戶都是合法的。

    這裏單獨加個用戶管理的服務,不在IAuthenticateService這個服務裏面添加相應邏輯,主要遵循了職責單一原則。首先和上面同樣,建立一個服務接口IUserService

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

    實現IUserService接口

public class UserService : IUserService
    {
        //模擬測試,默認都是人爲驗證有效
        public bool IsValid(LoginRequestDTO req)
        {
            return true;
        }
    }

    一樣註冊到容器中

services.AddScoped<IUserService, UserService>();

    接下來,就要完善TokenAuthenticationService簽發token的邏輯,首先要注入IUserService 和 TokenManagement,而後實現具體的業務邏輯,這個token的生成仍是使用的Jwt的類庫提供的api,具體不詳細描述。

特別注意下TokenManagement的注入是已IOptions的接口類型注入的,還記得在Startpup中嗎?咱們是經過配置項的方式註冊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;

        }
    }

  準備好測試試用的APi,打上Authorize特性,代表須要受權!

[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();
        }
    }

    支持咱們能夠測試驗證了,咱們能夠使用postman來進行http請求,先啓動http服務,獲取url,先測試一個訪問須要受權的接口,但沒有攜帶token信息,返回是401,表示未受權

    下面咱們先經過認證接口,獲取token,竟然報錯,查詢了下,發現HS256算法的祕鑰長度最新爲128位,轉換成字符至少16字符,以前設置的祕鑰是123456,因此致使異常。

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
    }

    從新發起請求,成功獲取token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJleHAiOjE1Nzg2NDUyMDMsImlzcyI6IndlYmFwaS5jbiIsImF1ZCI6IldlYkFwaSJ9.AehD8WTAnEtklof2OJsvg0U4_o8_SjdxmwUjzAiuI-o

    把token帶到以前請求的api中,從新測試,成功獲取數據

總結

    基於token的認證方式,讓咱們構建分佈式/鬆耦合的系統更加容易。任何地方生成的token,只有擁有相同祕鑰,就能夠再任何地方進行簽名校驗。

    固然要用好jwt認證方式,還有其餘安全細節須要處理,好比palyload中不能存放敏感信息,使用https的加密傳輸方式等等,能夠根據業務實際須要再進一步安全加固!

   同時咱們也發現使用token,就能夠擺脫cookie的限制,因此JWT是移動app開發的首選!

相關文章
相關標籤/搜索