1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- using Microsoft.Extensions.Configuration;
- using Microsoft.IdentityModel.Tokens;
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Security.Claims;
- using System.Text;
- using System.Threading.Tasks;
- namespace SMP.Common.Auth
- {
- public static class JWTHelper
- {
- public static string CreateToken(IConfiguration configuration, UserDto user)
- {
- // 1. 定义需要使用到的Claims
- var claims = new[]
- {
- new Claim(ClaimTypes.Name,user.userNickName),
- new Claim(ClaimTypes.Role, string.Join( ',',user.roles)),
- new Claim(ClaimTypes.NameIdentifier,user.token)
- };
- // 2. 从 appsettings.json 中读取SecretKey
- var secretKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"]));
- // 3. 选择加密算法
- var algorithm = SecurityAlgorithms.HmacSha256;
- // 4. 生成Credentials
- var signingCredentials = new SigningCredentials(secretKey, algorithm);
- // 5. 从 appsettings.json 中读取Expires
- var expires = Convert.ToDouble(configuration["JWT:Expires"]);
- // 6. 根据以上,生成token
- var token = new JwtSecurityToken(
- configuration["JWT:Issuer"], //Issuer
- configuration["JWT:Audience"], //Audience
- claims, //Claims,
- DateTime.Now, //notBefore
- DateTime.Now.AddDays(expires), //expires
- signingCredentials //Credentials
- );
- // 7. 将token变为string
- var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
- return jwtToken;
- }
- }
- }
|