.NET Core 实现 JWT 认证

写在前面

JWT(JSON Web Token)是一种开放标准, 由三部分组成,分别是Header、Payload和Signature,它以 JSON 对象的方式在各方之间安全地传输信息。通俗的说,就是通过数字签名算法生产一个字符串,然后在网络请求的中被携带到服务端进行身份认证,功能上来说和 SessionId 认证方式很像。

在.Net Core 中使用JWT 可以通过 NuGet 获取 Microsoft.AspNetCore.Authentication.JwtBearer 包。

另外JWT需要配置一个Key, 需要提前生成好;在上一篇中介绍过:

用keytool 生成JWT的RSA非对称密钥-CSDN博客

代码实现

appsettings.json 中的配置

javascript 复制代码
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Jwt": {
    "Key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArLhdR+Df8J9jNN4xuF9eqtbmibTpLaj1Re/e2aCuCFtVTfDgKsHklSSC4O8Jq0cyEBKs/SGhP8DD3w9vgFuWbpUcoYsWAEaV0zjWtJtng+upcpa4VTgi2jLltht+ukTs3f5uUsAXQT8pbBLyBZEcKZ1AuvFZCasG6BYPOJSiypQIeCWo0nq4u3cyaX4C5qjdhacxtT7RVXtQ5nWnMQxP+Mq2mf5x/zWEcCDhPFM5w7ulkcGOoWSCA3lRMOFB7fX49shBLgKAkATsSEB+EtmpWdbyI1pbRMqteWPELMLEB8EuJ0IEI4LRC59rlh/aQYHmyZnAKR", // 密钥
    "Issuer": "rjcql", // 颁发者
    "Audience": "rjcql" // 接收者
  }
}

代码主体:

cs 复制代码
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
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 = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey
        (Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = false,
        ValidateIssuerSigningKey = true
    };
});
builder.Services.AddAuthorization();

var app = builder.Build();

app.UseHttpsRedirection();
app.MapGet("/", () => "Hello everyone.");
app.MapGet("/security/getMessage", () => "Hello rjcql!").RequireAuthorization();
app.MapPost("/security/createToken",
[AllowAnonymous] (User user) =>
{
    if (user.UserName == "rjcql" && user.Password == "111111")
    {
        var issuer = builder.Configuration["Jwt:Issuer"];
        var audience = builder.Configuration["Jwt:Audience"];
        var key = Encoding.ASCII.GetBytes
        (builder.Configuration["Jwt:Key"]);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[]
            {
                new Claim("Id", Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Email, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti,
                Guid.NewGuid().ToString())
            }),
            Expires = DateTime.UtcNow.AddMinutes(5),
            Issuer = issuer,
            Audience = audience,
            SigningCredentials = new SigningCredentials
            (new SymmetricSecurityKey(key),
            SecurityAlgorithms.HmacSha512Signature)
        };
        var tokenHandler = new JwtSecurityTokenHandler();
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var jwtToken = tokenHandler.WriteToken(token);
        var stringToken = tokenHandler.WriteToken(token);
        return Results.Ok(stringToken);
    }
    return Results.Unauthorized();
});

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

app.Run();


public class User
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

调用示例

运行站点

用postman获取token

使用token访问目标链接

相关推荐
码农君莫笑2 天前
Blazor项目中使用EF读写 SQLite 数据库
linux·数据库·sqlite·c#·.netcore·人机交互·visual studio
_oP_i2 天前
.NET Core 项目配置到 Jenkins
运维·jenkins·.netcore
A^mber4 天前
基于.NetCore 的 AI 识别系统的设计与实现
人工智能·.netcore
Jeffrey~~6 天前
.Net_比对Json文件是否一致
c#·json·.net·.netcore
吳所畏惧7 天前
C#轻松实现Winform监控文件夹变化以及监控文件新增、修改、删除、重命名等操作保姆级详细教程
开发语言·windows·c#·.net·.netcore
CS软件开发框架7 天前
C/S软件授权注册系统-轻量级WebApi服务器介绍
运维·服务器·visualstudio·c#·.net·.netcore
鸠摩智首席音效师8 天前
如何使用 Docker 容器化 .NET Core 应用程序 ?
docker·容器·.netcore
洱海之月8 天前
.Net Core框架创建一个Windows服务类型的应用程序
.netcore
洱海之月8 天前
.Net Core配置使用Log4Net日志记录
.netcore
张3蜂8 天前
.NET Core 各版本特点、差异及适用场景详解
asp.net·.net·.netcore