xuruiqian
2025-06-04 5955ac5715a811407e183042875fd1d130572d58
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
using System;
using System.Text;
using JWT;
using JWT.Serializers;
using JWT.Algorithms;
using JWT.Exceptions;
using GTech.Solution.Api.Domain.Model.SystemSettings;
 
namespace GTech.Solution.Api.Common.Common
{
    public static class TokenGenerator
    {
        private static string secret = "yokogawa";
 
        public static string GetToken(Userbasic u)
        {
            JWT.Algorithms.IJwtAlgorithm Algorithm = new JWT.Algorithms.HMACSHA256Algorithm();
            JWT.IJsonSerializer json = new JsonNetSerializer();
            JWT.IBase64UrlEncoder Base64 = new JWT.JwtBase64UrlEncoder();
 
            JwtEncoder en = new JwtEncoder(Algorithm, json, Base64);
            byte[] keyBytes = Encoding.UTF8.GetBytes(secret);
            return en.Encode(u, keyBytes);
        }
 
        public static Userbasic GetUserbasic(string token)
        {
            IJsonSerializer js = new JsonNetSerializer();
            JWT.IBase64UrlEncoder Base64 = new JWT.JwtBase64UrlEncoder();
            JwtDecoder en = new JwtDecoder(js, Base64);
            return en.DecodeToObject<Userbasic>(token);
        }
        
        public static string ValidateJwtToken(string token)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtAlgorithm alg = new HMACSHA256Algorithm();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
                var json = decoder.Decode(token, secret, true);
                //校验通过,返回解密后的字符串
                return json;
            }
            catch (TokenExpiredException)
            {
                throw new Exception("Session is expired, access is denied!");
            }
            catch (SignatureVerificationException)
            {
                throw new Exception("Signature verification has error, access is denied!");
            }
            catch (Exception)
            {
                throw new Exception("Unauthorized user, Access is denied!");
            }
        }
    }
}