在Asp.Net Core Web API中使用JWT鑒權(2)使用JWT鑒權


本文承接上一篇在Asp.Net Core Web API中使用JWT鑒權(1)創建鑒權中心

1、創建Asp.Net Core Web API項目

這里使用的環境是VS2019 + .Net Core 3.1。
2、在Startup中注冊JWT鑒權
(1) 使用Nuget安裝Microsoft.AspNetCore.Authentication.JwtBearer。
(2) 注冊JWT鑒權

#region 注冊JWT鑒權
var issuer = Configuration["issuer"];
var audience = Configuration["audience"];
var securityKey = Configuration["SecurityKey"];
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //默認授權機制名稱
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true, //是否驗證Issuer
            ValidateAudience = true, //是否驗證Audience
            ValidateLifetime = true, //是否驗證失效時間
            ValidateIssuerSigningKey = true, //是否驗證IssuerSigningKey
            ValidAudience = audience,
            ValidIssuer = issuer,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)),
            //自定義校驗規則:新登錄后,之前的token無效
            //AudienceValidator = (audiences, securityToken, validationParameters) =>
            //{
            //    return audiences != null && audiences.FirstOrDefault().Equals(audience);
            //}
        };
    });
#endregion

(3) 啟用鑒權中間件

//啟用鑒權中間件
app.UseAuthentication();

3、添加JWT配置信息(appsettings.json)

"issuer": "http://localhost:9527",
"audience": "http://localhost:9527",
"SecurityKey": "4A9A70D2-B8AD-42E1-B002-553BDEF4E76F"

注意issuer、audience、SecurityKey要和鑒權中心的配置保持一致。

4、在控制器的接口中使用[Authorize]屬性 

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Security.Claims;

namespace TestWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        [Route("GetAuthData")]
        [Authorize]
        public IActionResult GetAuthData()
        {
            var claims = HttpContext.AuthenticateAsync().Result.Principal.Claims;
            var name = claims.FirstOrDefault(t => t.Type.Equals(ClaimTypes.Name))?.Value;
            var exp = claims.FirstOrDefault(t => t.Type.Equals("exp"))?.Value;

            var expDateTime = DateTime.Now;
            if (!string.IsNullOrWhiteSpace(exp))
            {
                long expValue;
                if (long.TryParse(exp, out expValue))
                {
                    expDateTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local);
                    expDateTime = expDateTime.AddSeconds(expValue);
                }
            }

            Console.WriteLine($"name: {name}, expDateTime: {expDateTime}");

            return new JsonResult(new
            {
                ExpDateTime = expDateTime,
                Name = name,
                Data = "已授權",
                Type = "GetAuthorizeData"
            });
        }
    }
}

 5、運行

(1) 運行Web API項目,在Postman中輸入http://localhost:5000/api/Test/GetAuthData,正常情況下會有401 Unauthorized錯誤。
(2) 在Postman的Authorization選項卡中選擇"Bearer Token",並輸入鑒權中心登錄后的token,正常情況下會輸出類似下面的內容:

{
    "expDateTime": "2021-02-22T10:02:25+08:00",
    "name": "admin",
    "data": "已授權",
    "type": "GetAuthorizeData"
}

 


免責聲明!

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



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