zhaolei
2020-11-20 921de2254ff5712a44ed8575ee8efe34252f6603
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
 
namespace Bootstrap.Security.Authentication
{
    /// <summary>
    /// BootstrapAdmin JWT 授权操作类
    /// </summary>
    public static class BootstrapAdminJwtTokenHandler
    {
        /// <summary>
        /// 通过指定用户名创建 JWT Token
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="configure">Token 配置信息</param>
        /// <returns>Json Web Token (JWT)</returns>
        public static string CreateToken(string userName, Action<TokenValidateOption>? configure = null)
        {
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, userName));
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenOption = new TokenValidateOption();
            configure?.Invoke(tokenOption);
            return tokenHandler.CreateEncodedJwt(new SecurityTokenDescriptor()
            {
                Issuer = tokenOption.Issuer,
                Audience = tokenOption.Audience,
                Subject = identity,
                Expires = DateTime.Now.AddMinutes(tokenOption.Expires),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOption.SecurityKey)), SecurityAlgorithms.HmacSha256)
            });
        }
    }
}