-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.go
More file actions
170 lines (144 loc) · 3.9 KB
/
jwt.go
File metadata and controls
170 lines (144 loc) · 3.9 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package goauthlib
import (
"crypto/sha3"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
"log"
"net/http"
"strings"
)
type JWTConfig struct {
signingMethod jwt.SigningMethod
signingKey any
verificationKey any
blinder string
}
func (config JWTConfig) SigningMethod() jwt.SigningMethod {
return config.signingMethod
}
func (config JWTConfig) SigningKey() any {
return config.signingKey
}
func (config JWTConfig) VerificationKey() any {
return config.verificationKey
}
func (config JWTConfig) Blinder() string {
return config.blinder
}
func (config JWTConfig) Copy() JWTConfig {
return JWTConfig{
signingMethod: config.signingMethod,
signingKey: config.signingKey,
verificationKey: config.verificationKey,
blinder: config.blinder,
}
}
func NewJWTConfig(signingMethod jwt.SigningMethod, signingKey any, verificationKey any, blinder string) *JWTConfig {
return &JWTConfig{signingMethod: signingMethod, signingKey: signingKey, verificationKey: verificationKey, blinder: blinder}
}
func (config JWTConfig) GenerateTokenFromModel(model User) (string, error) {
hash := GenerateTokenHash(model, config.blinder)
claims := struct {
Hash string `json:"hash"`
User User `json:"user"`
jwt.RegisteredClaims
}{hash,
model,
jwt.RegisteredClaims{
Issuer: "auth",
},
}
tokenObj := jwt.NewWithClaims(config.signingMethod, claims)
token, err := tokenObj.SignedString(config.signingKey)
if err != nil {
return "", err
}
return token, nil
}
func (config JWTConfig) GetClaimsFromToken(token string) (map[string]any, error) {
tokenObj, err := jwt.ParseWithClaims(token, &jwt.MapClaims{}, func(token *jwt.Token) (any, error) {
if token.Method.Alg() != config.signingMethod.Alg() {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return config.verificationKey, nil
})
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
log.Printf("Token is expired")
return nil, err
}
log.Printf("Failed to parse token: %s", err.Error())
return nil, err
}
if !tokenObj.Valid {
log.Printf("Token is invalid")
return nil, errors.New("invalid token")
}
// Safely access the claims
claims, ok := tokenObj.Claims.(*jwt.MapClaims)
if !ok {
log.Printf("Invalid claims type")
}
return *claims, nil
}
func GenerateTokenHash(model User, blinder string) string {
sha := sha3.New256()
bytes, err := hex.DecodeString(model.ID)
if err != nil {
panic(err)
}
bytes = append(bytes, []byte(blinder)...)
_, err = sha.Write(bytes)
if err != nil {
panic(err)
}
return hex.EncodeToString(sha.Sum(nil))
}
func (config JWTConfig) SafeExtractUserIdFromHeader(h http.Header) (string, error) {
// Check if Authorization header exists
authHeader, ok := h["Authorization"]
if !ok || len(authHeader) == 0 {
return "", errors.New("authorization header is missing")
}
// Split the Authorization header into parts
tokenParts := strings.Split(authHeader[0], " ")
if len(tokenParts) != 2 || tokenParts[0] != "JWT" {
return "", errors.New("invalid Authorization header format")
}
token := tokenParts[1]
claims, err := config.GetClaimsFromToken(token)
if err != nil {
return "", err
}
user, ok := claims["user"].(map[string]any)
if !ok {
return "", errors.New("user claim is missing or invalid")
}
userIdFromJwt, ok := user["id"].(string)
if !ok {
return "", errors.New("user ID is missing or invalid")
}
return userIdFromJwt, nil
}
func (config JWTConfig) GetValidUserFromToken(token string) (*User, error) {
claims, err := config.GetClaimsFromToken(token)
if err != nil {
return nil, err
}
userBytes, err := json.Marshal(claims["user"])
if err != nil {
return nil, err
}
var user User
err = json.Unmarshal(userBytes, &user)
if err != nil {
return nil, err
}
if GenerateTokenHash(user, config.blinder) != claims["hash"] {
return nil, errors.New("invalid token hash")
}
return &user, nil
}