chenhaozhe
2 天以前 3ee33d4728add92460a71c05d36cf24b5fdd903c
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
 
namespace WebAPI.Utility
{
    public static class JWTHelper
    {
        static JWTHelper()
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        }
 
        // 秘钥
        private const string SecretKey = "8sK2pR9vFg5tHjNm7qWaEe4dUcxZbL$S6y";
        private static readonly SymmetricSecurityKey _securityKey =
        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
 
        // 签发 Token
        public static string GenerateToken(string userId, string userName, string HCampanyName)
        {
            var claims = new[]
            {
            new Claim(ClaimTypes.NameIdentifier, userId),
            new Claim(ClaimTypes.Name, userName),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };
 
            var credentials = new SigningCredentials(_securityKey, SecurityAlgorithms.HmacSha256);
 
            var token = new JwtSecurityToken(
                issuer: "zjzyms",
                audience: HCampanyName,
                claims: claims,
                expires: DateTime.UtcNow.AddHours(2), // 两小时过期时间
                signingCredentials: credentials
            );
 
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
 
        // 验证 Token 并返回 ClaimsPrincipal
        public static ClaimsPrincipal ValidateToken(string token, string HCampanyName)
        {
            var handler = new JwtSecurityTokenHandler();
 
            var parameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = "zjzyms",
 
                ValidateAudience = true,
                ValidAudience = HCampanyName,
 
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _securityKey,
 
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero, // 不允许时间误差
            };
 
           
            try
            {
                var principal = handler.ValidateToken(token, parameters, out var validatedToken);
                return principal;
            }
            catch
            {
                return null;
            }
        }
    }
}