.net core 3.1 jwt token授權


.net core 3.1 引入jwt 授權,在這篇文章“ASP.Net Core 3.1 中使用JWT認證” 已經做了總結,只是復制粘貼自己跑一遍

首先安裝 Microsoft.AspNetCore.Authentication.JwtBearer

核心代碼是這段:

public class AuthenticationService : IAuthenticateService

    {

        private readonly ITestService _testService;

        private readonly TokenManagement _tokenManagement;

        public AuthenticationService(ITestService testService, IOptions<TokenManagement> tokenManagement)

        {

            _testService = testService;

            _tokenManagement = tokenManagement.Value;

        }

        public bool IsAuthenticated(LoginRequestDTO request, out string token)

        {

            token = string.Empty;

            //此處做驗證

            if (!_testService.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; 

        }

    }

  

可以結合request參數,在 _testService.IsValid(request) 接口做驗證

LoginRequestDTO 類定義request傳參

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

[Required]
[JsonProperty("password")]
public string Password { get; set; }
}

 

TokenManagement 類定義 jwt 相關參數

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; }

    }

tokenManagement 配置在appsettings.json

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

 

 

此外,修改Startup.cs 文件

在ConfigService方法中增加這段代碼

services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();

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 方法中增加 這段授權代碼

app.UseAuthentication();

 

最后,在要調用的方法中,添加屬性 [Authorize],就可以增加token驗證了;也可以在控制器上添加,那么該控制器下所有接口都要驗證。

 

ASP.Net Core 3.1 中使用JWT認證


免責聲明!

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



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