什么是 JWT ?
从 https://jwt.io/ 可以了解到对 JWT 的描述:JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
JWT 是一个开放的,RFC 7519 工业标准方法,用来在两个部分之间表示安全声明。
下面来看一个 JWT 的例子:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjEyMjAiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi55So5oi3NTk4OCIsImlzcyI6IkhaRyIsImF1ZCI6IkhaRyJ9.ipS3XPIF6QFm98olSaQzdqQ5vVrIR-_ACgaBFt0AFCg
上面是一个 JWT。可以看到,整体被两个点分为三部分,依次为 header,payload,加密部分。
header 部分:
base64 编码,这部分可以通过 base64 解码得到,示例中的解码后为:
{
"alg": "HS256",
"typ": "JWT"
}
其中,alg 表示服务端加密所用的算法,typ 表示 token 为 JWT
payload 部分代表附加的信息,可以传递一些用户信息等,也是 base 64 编码,示例中解析后为 :
{
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "1220",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "用户5988",
"iss": "HZG",
"aud": "HZG"
}
都是一些声明,可以在生成 JWT 的时候声明。
第三部分是加密部分,也就是使用 header 中的算法,把 header 和 payload 部分加密,用来验证传递的信息是否被修改。
如何在 ASP.NET Core 中集成 JWT?
首先我们需要考虑的是要实现什么功能?我们这里只是实现了简单的 JWT 签发功能,不做过多讨论
- 生成 token
IJwtService.cs
using System.Threading.Tasks; namespace JWTSample.Jwt; /// <summary> /// Jwt 功能接口 /// </summary> public interface IJwtService { // 生成 JWT token string GetnerateJWTToken(UserDto userDto); }
JwtService.cs
using System; using System.Linq; using System.IdentityModel.Tokens.Jwt; using System.Text; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Http; namespace JWTSample.Jwt; /// <summary> /// JWT 功能类 /// </summary> public class JwtService : IJwtService { // 配置 private readonly IConfiguration _configuration; public JwtService(IConfiguration configuration) { _configuration = configuration; } /// <summary> /// 生成 JWT /// </summary> /// <param name="userDto">用户信息</param> /// <returns></returns> public string GetnerateJWTToken(UserDto userDto) { var claims = new Claim[] { new Claim(ClaimTypes.Name, userDto.UserName), new Claim(ClaimTypes.Role, userDto.Roles), // 用户所在的分组 new Claim("groups", userDto.Groups) }; var issuer = _configuration[JwtOptionsConst.IssuerSettingPath]; var audience = _configuration[JwtOptionsConst.AudienceSettingPath]; var security = _configuration[JwtOptionsConst.SecurityKeySettingPath]; var expires = DateTime.Now.AddHours(Convert.ToDouble(_configuration[JwtOptionsConst.ExpiresHourSettingPath])); SymmetricSecurityKey symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(security)); var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256); var jwtSecurityToken = new JwtSecurityToken(claims: claims, issuer: issuer, audience: audience, expires: expires, signingCredentials: signingCredentials); var tokenHandler = new JwtSecurityTokenHandler(); return tokenHandler.WriteToken(jwtSecurityToken); } }
如何使用?我们可以直接在控制器中注入使用
using System; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using System.Security.Claims; using System.IdentityModel.Tokens.Jwt; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using JWTSample.Jwt; using JWTSample.Models; namespace JWTSample.Controllers; public class AuthController : Controller { private readonly IJwtService _jwtService; public AuthController(IJwtService jwtService) { _jwtService = jwtService; } [AllowAnonymous] [HttpPost] public IActionResult Login([FromBody] LoginUserInfo loginUserInfo) { if (loginUserInfo.Name == null) { return Ok(new { Message = "用户名不能为空!" }); } var userDto = new UserDto() { UserId = new Random().Next(1000), UserName = loginUserInfo.Name, Groups = "技术部", Roles = "软件工程师", Email = "[email protected]", Phone = "123456789" }; var token = _jwtService.GetnerateJWTToken(userDto); return Ok(new { Token = token }); } }