|
| 1 | +package jwt_manager |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/hmac" |
| 5 | + "crypto/sha256" |
| 6 | + "encoding/base64" |
| 7 | + "encoding/json" |
| 8 | + "errors" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +type Manager interface { |
| 14 | + Generate(audience, subject string, custom map[string]interface{}) string |
| 15 | + IsValid(token string) (bool, error) |
| 16 | + IsOnTime(token string) (bool, error) |
| 17 | + TokenNeedsRefresh(token string) (bool, error) |
| 18 | + DecodePayload(token string) (map[string]interface{}, error) |
| 19 | +} |
| 20 | + |
| 21 | +var _ Manager = (*JwtManager)(nil) |
| 22 | + |
| 23 | +type JwtManager struct { |
| 24 | + AppSecret string |
| 25 | + Context string |
| 26 | + Expire int64 |
| 27 | + Renew int64 |
| 28 | + algorithm string |
| 29 | + tokenType string |
| 30 | +} |
| 31 | + |
| 32 | +func NewJwtManager(secret, context string, expire, renew int64) Manager { |
| 33 | + return &JwtManager{ |
| 34 | + AppSecret: secret, |
| 35 | + Context: context, |
| 36 | + Expire: expire, |
| 37 | + Renew: renew, |
| 38 | + algorithm: "HS256", |
| 39 | + tokenType: "JWT", |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func (j *JwtManager) GetHeader() string { |
| 44 | + header := map[string]string{ |
| 45 | + "alg": j.algorithm, |
| 46 | + "typ": j.tokenType, |
| 47 | + } |
| 48 | + data, _ := json.Marshal(header) |
| 49 | + return Base64UrlEncode(data) |
| 50 | +} |
| 51 | + |
| 52 | +func (j *JwtManager) getPayload(audience, subject string, custom map[string]interface{}) string { |
| 53 | + now := time.Now().Unix() |
| 54 | + payload := map[string]interface{}{ |
| 55 | + "aud": audience, |
| 56 | + "exp": now + j.Expire, |
| 57 | + "iat": now, |
| 58 | + "iss": j.Context, |
| 59 | + "sub": subject, |
| 60 | + } |
| 61 | + for k, v := range custom { |
| 62 | + payload[k] = v |
| 63 | + } |
| 64 | + data, _ := json.Marshal(payload) |
| 65 | + return Base64UrlEncode(data) |
| 66 | +} |
| 67 | + |
| 68 | +func (j *JwtManager) GetSignature(header, payload string) string { |
| 69 | + h := hmac.New(sha256.New, []byte(j.AppSecret)) |
| 70 | + h.Write([]byte(header + "." + payload)) |
| 71 | + return Base64UrlEncode(h.Sum(nil)) |
| 72 | +} |
| 73 | + |
| 74 | +func (j *JwtManager) Generate(audience, subject string, custom map[string]interface{}) string { |
| 75 | + header := j.GetHeader() |
| 76 | + payload := j.getPayload(audience, subject, custom) |
| 77 | + signature := j.GetSignature(header, payload) |
| 78 | + return header + "." + payload + "." + signature |
| 79 | +} |
| 80 | + |
| 81 | +func (j *JwtManager) IsValid(token string) (bool, error) { |
| 82 | + parts := strings.Split(token, ".") |
| 83 | + if len(parts) != 3 { |
| 84 | + return false, errors.New("invalid JWT format") |
| 85 | + } |
| 86 | + expectedSig := j.GetSignature(parts[0], parts[1]) |
| 87 | + if parts[2] != expectedSig && parts[2] != expectedSig+"=" { |
| 88 | + return false, errors.New("invalid JWT signature") |
| 89 | + } |
| 90 | + return true, nil |
| 91 | +} |
| 92 | + |
| 93 | +func (j *JwtManager) IsOnTime(token string) (bool, error) { |
| 94 | + payload, err := j.DecodePayload(token) |
| 95 | + if err != nil { |
| 96 | + return false, errors.New("Illegal base64") |
| 97 | + } |
| 98 | + exp, ok := payload["exp"].(float64) |
| 99 | + if !ok || int64(exp) < time.Now().Unix() { |
| 100 | + return false, errors.New("JWT expired") |
| 101 | + } |
| 102 | + return true, nil |
| 103 | +} |
| 104 | + |
| 105 | +func (j *JwtManager) TokenNeedsRefresh(token string) (bool, error) { |
| 106 | + payload, err := j.DecodePayload(token) |
| 107 | + if err != nil { |
| 108 | + return false, errors.New("Illegal base64") |
| 109 | + } |
| 110 | + iat, ok := payload["iat"].(float64) |
| 111 | + if !ok { |
| 112 | + return false, errors.New("invalid JWT payload: missing iat") |
| 113 | + } |
| 114 | + if time.Now().Unix() > int64(iat)+j.Renew { |
| 115 | + return true, nil |
| 116 | + } |
| 117 | + return false, nil |
| 118 | +} |
| 119 | + |
| 120 | +func (j *JwtManager) DecodePayload(token string) (map[string]interface{}, error) { |
| 121 | + parts := strings.Split(token, ".") |
| 122 | + if len(parts) != 3 { |
| 123 | + return nil, errors.New("invalid token format") |
| 124 | + } |
| 125 | + payloadJson, err := Base64UrlDecode(parts[1]) |
| 126 | + if err != nil { |
| 127 | + return nil, errors.New("Illegal base64") |
| 128 | + } |
| 129 | + var payload map[string]interface{} |
| 130 | + err = json.Unmarshal([]byte(payloadJson), &payload) |
| 131 | + if err != nil { |
| 132 | + return nil, errors.New("Illegal payload") |
| 133 | + } |
| 134 | + return payload, nil |
| 135 | +} |
| 136 | + |
| 137 | +func Base64UrlEncode(data []byte) string { |
| 138 | + return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(data) |
| 139 | +} |
| 140 | + |
| 141 | +func Base64UrlDecode(data string) (string, error) { |
| 142 | + decoded, err := base64.URLEncoding.WithPadding(base64.NoPadding).DecodeString(data) |
| 143 | + return string(decoded), err |
| 144 | +} |
0 commit comments