.NET Core JWT 科普指南

简介

.NET Core 是一个跨平台的开源框架,用于构建现代化的Web应用程序和服务。JSON Web Token(JWT)则是一种用于进行身份验证和授权的开放标准。在.NET Core中,我们可以使用JWT来实现安全的身份验证和授权机制。

在本篇文章中,我们将介绍什么是JWT以及如何在.NET Core中使用JWT进行身份验证。

什么是JWT?

JWT是一种轻量级的安全传输协议,它由三个部分组成:头部(header)、负载(payload)和签名(signature)。头部包含了JWT的类型和使用的加密算法,负载包含了一些声明信息,比如用户ID、过期时间等,签名则用于验证JWT的完整性。

JWT的工作流程如下:

  1. 用户通过提供用户名和密码进行登录;
  2. 服务器验证用户提供的凭据,并生成一个JWT;
  3. 服务器将JWT返回给客户端;
  4. 客户端将JWT保存在本地;
  5. 客户端在后续的请求中,将JWT放在请求的头部或者请求参数中;
  6. 服务器接收到请求,验证JWT的有效性,并根据负载信息进行授权操作。

.NET Core中的JWT验证

在.NET Core中,我们可以使用System.IdentityModel.Tokens.Jwt库来实现JWT的生成和验证。

首先,我们需要在.NET Core应用程序中添加System.IdentityModel.Tokens.Jwt库的引用。可以通过NuGet包管理器或者在项目文件中手动添加引用:

dotnet add package System.IdentityModel.Tokens.Jwt

接下来,我们可以使用以下代码生成JWT:

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

public class JwtService
{
    private readonly string _secretKey;
    private readonly string _issuer;

    public JwtService(string secretKey, string issuer)
    {
        _secretKey = secretKey;
        _issuer = issuer;
    }

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

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            _issuer,
            _issuer,
            claims,
            expires: DateTime.Now.AddDays(7),
            signingCredentials: credentials
        );

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

在上述代码中,我们通过JwtSecurityTokenHandler类将JWT转换为字符串,并返回给客户端。GenerateToken方法接受用户ID和角色作为参数,生成带有相应声明的JWT。

接下来,我们可以在.NET Core控制器中使用JWT进行身份验证:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    [HttpGet("me")]
    public IActionResult GetCurrentUser()
    {
        var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        var role = User.FindFirst(ClaimTypes.Role)?.Value;

        return Ok(new { UserId = userId, Role = role });
    }
}

在上述代码中,我们使用[Authorize]特性标记了UserController,表示该控制器需要进行身份验证。在GetCurrentUser方法中,我们通过User对象来获取当前用户的ID和角色信息,并返回给客户端。

结论

使用JWT进行身份验证和授权是.NET Core中一种常见的实践。通过使用System.IdentityModel.Tokens.Jwt库,我们可以方便地生成和验证JWT。在控制器中,我们可以使用[Authorize]特性来标记需要进行身份验证的请求。

希望本篇文章能够帮助你了解并使用.NET Core中的JWT身份验证!