ASP.NET Core 入门教学十三 使用JWT进行身份验证

目录
  1. JWT简介
  2. 安装必要的NuGet包
  3. 配置JWT身份验证
  4. 创建用户认证服务
  5. 生成和验证JWT令牌
  6. 保护API端点
  7. 刷新令牌机制
  8. 最佳实践
正文内容
1. JWT简介

JWT由三部分组成:头部(Header)、载荷(Payload)和签名(Signature)。每一部分都是Base64编码的JSON字符串,并用点号(.)分隔。JWT的主要优点包括:

  • 自包含性:所有必要的信息都包含在令牌中,减少了服务器查询数据库的次数。
  • 安全性:通过签名确保数据的完整性和真实性。
  • 跨域支持:JWT可以在不同的域之间安全地传输。
2. 安装必要的NuGet包

首先,我们需要安装Microsoft.AspNetCore.Authentication.JwtBearer包,以便在ASP.NET Core中使用JWT。

复制代码
复制代码
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
3. 配置JWT身份验证

Startup.cs文件中,我们需要进行以下配置以启用JWT身份验证:

复制代码
cs 复制代码
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    // 配置JWT身份验证
    var key = Encoding.UTF8.GetBytes("your_secret_key"); // 替换为你的密钥
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    </tool>
4. 创建用户认证服务

我们需要创建一个用户认证服务来处理用户的登录请求并生成JWT令牌。

复制代码
cs 复制代码
public class AuthService
{
    private readonly IConfiguration _configuration;
    private readonly IMapper _mapper;

    public AuthService(IConfiguration configuration, IMapper mapper)
    {
        _configuration = configuration;
        _mapper = mapper;
    }

    public async Task<string> LoginAsync(UserForLoginDto userForLoginDto)
    {
        // 验证用户凭据
        var userFromRepo = await _userRepository.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

        if (userFromRepo == null)
            throw new Exception("Invalid username/password");

        // 生成JWT令牌
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Token").Value);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            }),
            Expires = DateTime.Now.AddDays(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var tokenString = tokenHandler.WriteToken(token);

        return tokenString;
    }
}
5. 生成和验证JWT令牌

在上面的AuthService中,我们已经展示了如何生成JWT令位,在Startup.cs文件中配置了如何验证JWT令牌。

6. 保护API端点

我们可以使用[Authorize]属性来保护API端点,确保只有经过身份验证的用户才能访问。

复制代码
复制代码
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    [HttpGet("{id}")]
    [Authorize]
    public async Task<IActionResult> Get(int id)
    {
        // 获取用户信息
    }
}
7. 刷新令牌机制

为了提高安全性,可以实现一个刷新令牌机制,允许用户在JWT令牌过期后获取新的令牌,而无需重新登录。

8. 最佳实践
  • 密钥管理:确保密钥的安全存储,不要硬编码在代码中。
  • 令牌过期时间:设置合理的令牌过期时间,平衡安全性和用户体验。
  • HTTPS:始终使用HTTPS来保护令牌在传输过程中的安全。
结语

通过本教程,我们学习了如何在ASP.NET Core项目中使用JWT实现安全的身份验证。JWT提供了一种强大且灵活的方式来管理用户身份和权限,希望你能将这些知识应用到实际项目中,提升应用的安全性和用户体验。

相关推荐
程序员爱钓鱼15 小时前
Go生成唯一ID的标准方案:github.com/google/uuid使用详解
后端·google·go
Moment15 小时前
MinIO已死,MinIO万岁
前端·后端·github
无双_Joney15 小时前
心路散文 - 转职遇到AI浪潮,AIGC时刻人的价值是什么?
前端·后端·架构
树獭叔叔16 小时前
OpenClaw Tools 与 Skills 系统深度解析
后端·aigc·openai
树獭叔叔16 小时前
OpenClaw Memory 系统深度解析:从文件到向量的完整实现
后端·aigc·openai
程序猿阿越16 小时前
Kafka4源码(二)创建Topic
java·后端·源码阅读
悟空码字16 小时前
Spring Boot 整合 MongoDB 最佳实践:CRUD、分页、事务、索引全覆盖
java·spring boot·后端
开心就好202516 小时前
iOS App 安全加固流程记录,代码、资源与安装包保护
后端·ios
省长16 小时前
Sa-Token v1.45.0 发布 🚀,正式支持 Spring Boot 4、新增 Jackson3/Snack4 插件适配
java·后端·开源
开心就好202516 小时前
iOS App 性能测试工具怎么选?使用克魔助手(Keymob)结合 Instruments 完成
后端·ios