-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_helper.go
131 lines (107 loc) · 2.89 KB
/
jwt_helper.go
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
package jwt
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"math/big"
"net/http"
"strconv"
"github.com/wissemmansouri/OpenIT.one-Common/model"
"github.com/wissemmansouri/OpenIT.one-Common/utils/common_err"
"github.com/gin-gonic/gin"
)
type JWK struct {
Kty string `json:"kty"`
Crv string `json:"crv"`
X string `json:"x"`
Y string `json:"y"`
}
type JWKS struct {
Keys []JWK `json:"keys"`
}
const JWKSPath = ".well-known/jwks.json"
func ExceptLocalhost(publicKeyFunc func() (*ecdsa.PublicKey, error)) gin.HandlerFunc {
return func(c *gin.Context) {
if c.ClientIP() == "::1" || c.ClientIP() == "127.0.0.1" {
c.Next()
return
}
JWT(publicKeyFunc)(c)
}
}
func JWT(publicKeyFunc func() (*ecdsa.PublicKey, error)) gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if len(token) == 0 {
token = c.Query("token")
}
valid, claims, err := Validate(token, publicKeyFunc)
if err != nil || !valid {
message := "token is invalid"
c.JSON(http.StatusUnauthorized, model.Result{Success: common_err.ERROR_AUTH_TOKEN, Message: message})
c.Abort()
return
}
c.Request.Header.Add("user_id", strconv.Itoa(claims.ID))
c.Next()
}
}
func GenerateKeyPair() (*ecdsa.PrivateKey, *ecdsa.PublicKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, fmt.Errorf("error generating key pair: %w", err)
}
publicKey := &privateKey.PublicKey
return privateKey, publicKey, nil
}
func GenerateJwksJSON(publicKey *ecdsa.PublicKey) ([]byte, error) {
jwk := JWK{
Kty: "EC",
Crv: "P-256",
X: base64.RawURLEncoding.EncodeToString(publicKey.X.Bytes()),
Y: base64.RawURLEncoding.EncodeToString(publicKey.Y.Bytes()),
}
jwks := JWKS{
Keys: []JWK{jwk},
}
return json.Marshal(jwks)
}
func PublicKeyFromJwksJSON(jwksJSON []byte) (*ecdsa.PublicKey, error) {
var jwks JWKS
err := json.Unmarshal(jwksJSON, &jwks)
if err != nil {
return nil, fmt.Errorf("error unmarshalling JWKS JSON: %w", err)
}
if len(jwks.Keys) == 0 {
return nil, fmt.Errorf("no keys in JWKS")
}
jwk := jwks.Keys[0]
x, err := base64.RawURLEncoding.DecodeString(jwk.X)
if err != nil {
return nil, fmt.Errorf("error decoding X: %w", err)
}
y, err := base64.RawURLEncoding.DecodeString(jwk.Y)
if err != nil {
return nil, fmt.Errorf("error decoding Y: %w", err)
}
publicKey := &ecdsa.PublicKey{
Curve: elliptic.P256(),
X: new(big.Int).SetBytes(x),
Y: new(big.Int).SetBytes(y),
}
return publicKey, nil
}
func JWKSHandler(jwksJSON []byte) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err := w.Write(jwksJSON)
if err != nil {
http.Error(w, "Error writing JWKS JSON", http.StatusInternalServerError)
return
}
})
}