在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"
}

 

posted @   xhubobo  阅读(792)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
点击右上角即可分享
微信分享提示