.NET Core Web API项目配置JWT验证

前言

本项目在之前的文章中已搭建完成,所有内容在之前的项目中扩展
之前的文章地址:跳转地址
源码下载地址:下载地址
JSON WEB Token(JWT),是一种基于JSON的、用于在网络上声明某种主张的令牌(token)。主要用于认证和保护API之间信息交换。JWT通常由三部分组成: 头信息(header), 消息体(payload)和签名(signature)。项目多使用JWT来进行身份验证。


使用JWT步骤

1安装 Microsoft.AspNetCore.Authentication.JwtBearer ,可通过Nuget包管理器进行安装,如下所示:
在这里插入图片描述
2 在appsettings.json添加JWT配置

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",

  "Jwt": {
    "SecretKey": "c0ecd23c-dfdb-4005-a2ea-0fea210c858d",
    "Issuer": "JwtIssuer",
    "Audience": "JwtAudience"
  }
}

3 在Program.cs文件中添加JWT身份验证服务

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

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
    o.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = TS.Common.Helpers.Appsettings.GetValue("Jwt", "Issuer"),
        ValidAudience = TS.Common.Helpers.Appsettings.GetValue("Jwt", "Audience"),
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TS.Common.Helpers.Appsettings.GetValue("Jwt", "SecretKey"))),
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = false,
        ValidateIssuerSigningKey = true
    };
});
builder.Services.AddAuthorization();

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "请输入token,格式为 Bearer xxxxxxxx",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    //添加安全要求
    options.AddSecurityRequirement(new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme{
                Reference =new OpenApiReference{
                    Type = ReferenceType.SecurityScheme,
                    Id ="Bearer"
                }
            },new string[]{ }
        }
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

4 在TS.Common中添加Microsoft.Extensions.Configuration.Json包

在这里插入图片描述
5 在TS.Common中添加Appsettings.cs

代码如下:

using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Configuration;

namespace TS.Common.Helpers
{
    /// <summary>
    /// appsettings.json操作类
    /// </summary>
    public class Appsettings
    {
        static IConfiguration? configuration { get; set; }
        static string? contentPath { get; set; }

        public Appsettings(string contentPath)
        {
            string Path = "appsettings.json";

            configuration = new ConfigurationBuilder()
               .SetBasePath(contentPath)
               .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })
               .Build();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sections"></param>
        /// <returns>String</returns>
        public static string GetValue(params string[] sections)
        {
            Appsettings appsettingsinfo = new Appsettings(AppContext.BaseDirectory);

            return configuration?[string.Join(":", sections)] ?? String.Empty;
        }

    }
}

6 创建Token,代码如下

        private static string GenerateJsonWebToken()
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TS.Common.Helpers.Appsettings.GetValue("Jwt", "SecretKey")));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            claimsIdentity.AddClaim(new Claim("userid", "1"));
            var token = new JwtSecurityToken(TS.Common.Helpers.Appsettings.GetValue("Jwt", "Issuer"),
              TS.Common.Helpers.Appsettings.GetValue("Jwt", "Audience"),
              claimsIdentity.Claims,
              expires: DateTime.Now.AddMinutes(120),
              signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }


        /// <summary>
        /// 创建Token
        /// </summary>
        /// <returns></returns>
        [HttpPost("GenerateToken")]
        public ActionResult GetToken()
        {
            string token = GenerateJsonWebToken();
            return Ok(token);
        }

7 验证JWT是否配置成功,编写验证接口

        /// <summary>
        /// 验证Token
        /// </summary>
        /// <returns></returns>
        [Authorize] //开启授权验证
        [HttpPost("TestToken")]
        public ActionResult Test()
        {
            return Ok("成功进入");
        }

8 Herder中带验证参数(GetToken接口获取的参数 前面加上 Bearer )
在这里插入图片描述
9 如果没有传入Token 调用接口将报401错误。

10 当然直接在swagger中调用也可以,需要配置Authorization参数
在这里插入图片描述


总结

使用JWT进行身份验证有很多优点,当然JWT也有缺点
例如 更多的空间占用、无法作废已颁布的令牌、Payload 存储的一些用户信息,它是通过Base64加密的,可以直接解密等


相关推荐

  1. Python Totp 验证,JWT 验证

    2024-07-22 09:00:03       51 阅读
  2. gin使用jwt登录验证

    2024-07-22 09:00:03       58 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 09:00:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 09:00:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 09:00:03       45 阅读
  4. Python语言-面向对象

    2024-07-22 09:00:03       55 阅读

热门阅读

  1. 1.关于linux的命令

    2024-07-22 09:00:03       15 阅读
  2. 配置php-fpm服务

    2024-07-22 09:00:03       19 阅读
  3. 【机器学习框架TensorFlow和PyTorch】基本使用指南

    2024-07-22 09:00:03       16 阅读
  4. 华为eNSP模拟器安装

    2024-07-22 09:00:03       16 阅读
  5. HTTP协议的演进:从HTTP/1.0到HTTP/2.0

    2024-07-22 09:00:03       14 阅读
  6. 在Ubuntu 14.04上安装和使用Docker Compose的方法

    2024-07-22 09:00:03       16 阅读
  7. 【自动化机器学习AutoML】AutoML工具和平台的使用

    2024-07-22 09:00:03       16 阅读
  8. 【数据挖掘基础】数据挖掘技术概述和基本算法

    2024-07-22 09:00:03       17 阅读
  9. 常用传感器误差补偿方法介绍

    2024-07-22 09:00:03       16 阅读
  10. ARM/Linux嵌入式面经(十七):美团校招面经

    2024-07-22 09:00:03       16 阅读
  11. 深度学习简介(框架)

    2024-07-22 09:00:03       16 阅读
  12. ChatGPT的工作记忆容量:一项实证研究

    2024-07-22 09:00:03       14 阅读
  13. AI学习指南机器学习篇-SOM的拓扑结构与参数调优

    2024-07-22 09:00:03       17 阅读
  14. 如何调整图像的窗宽窗位

    2024-07-22 09:00:03       16 阅读