使用ASP.NET Core实现JWT身份认证

微笑向暖 2024-07-26 ⋅ 11 阅读

概述

JWT(JSON Web Token)是一种开放标准(RFC 7519),用于在各方之间安全地传输信息。它由三部分组成:头部、载荷和签名。在身份认证中,JWT可以用于生成和验证令牌,以确认用户的身份。

本文将介绍如何在ASP.NET Core项目中使用JWT实现身份认证。

安装所需的NuGet包

首先,在ASP.NET Core项目中安装以下NuGet包:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt

配置JWT身份认证

在ASP.NET Core的Startup.cs文件中,找到ConfigureServices方法,并添加以下代码:

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

public void ConfigureServices(IServiceCollection services)
{
    // 配置JWT身份认证
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true, // 验证发行人
            ValidateAudience = true, // 验证订阅人
            ValidateIssuerSigningKey = true, // 验证签名密钥
            ValidAudience = "your-audience", // 有效的订阅人
            ValidIssuer = "your-issuer", // 有效的发行人
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key")) // 签名密钥
        };
    });

    services.AddControllers();
}

其中,your-audienceyour-issuer应替换为实际的订阅人和发行人,your-secret-key应替换为实际的密钥。

生成JWT令牌

要生成JWT令牌,可以使用System.IdentityModel.Tokens.Jwt命名空间中的JwtSecurityTokenHandler类。例如,下面的代码生成一个包含用户ID和角色的JWT令牌:

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

public string GenerateJwtToken(string userId, string role)
{
    var claims = new[]
    {
        new Claim(ClaimTypes.NameIdentifier, userId),
        new Claim(ClaimTypes.Role, role)
    };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
    var token = new JwtSecurityToken(
        issuer: "your-issuer",
        audience: "your-audience",
        claims: claims,
        expires: DateTime.Now.AddDays(7),
        signingCredentials: credentials
    );

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

在此代码中,your-secret-keyyour-issueryour-audience应替换为实际的密钥、发行人和订阅人。

验证JWT令牌

在需要进行身份验证的控制器或方法上,可以使用[Authorize]特性来要求用户进行身份认证。例如:

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
    // ...
}

在身份验证成功后,可以获取用户的身份信息,例如用户ID和角色:

var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var role = User.FindFirst(ClaimTypes.Role)?.Value;

总结

在本文中,我们了解了如何使用ASP.NET Core来实现JWT身份认证。首先,我们配置了JWT身份认证,然后介绍了如何生成JWT令牌和验证其有效性。最后,我们说明了如何在控制器中进行身份验证,并获取用户的身份信息。希望这篇文章能够帮助您快速上手JWT身份认证的实践。


全部评论: 0

    我有话说: