-
Notifications
You must be signed in to change notification settings - Fork 4
/
token.go
61 lines (49 loc) · 1.35 KB
/
token.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
package jwtpxy
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"github.com/golang-jwt/jwt"
"go.uber.org/zap"
)
type TokenMapping struct {
Header string
TokenKey string
TokenValue interface{}
}
func (p *Proxy) ProxyTokenHandler(r *http.Request, tokenString string) error {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// WARNING: always validate that the alg is what we expect
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return p.JWTConfig.PublicKey, nil
})
if err != nil {
return err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
r.Header.Add(StatusHeader, "valid")
for _, tknMap := range p.TokenMappings {
if claim, ok := claims[tknMap.TokenKey]; ok {
if reflect.TypeOf(claim).Kind() == reflect.String {
r.Header.Add(tknMap.Header, claim.(string))
r.Header.Add(HeadersHeader, tknMap.Header)
continue
}
claimJson, err := json.Marshal(claim)
if err != nil {
p.Logger.Error("unable to marshal claim", zap.Any("tknMap", tknMap), zap.Error(err))
continue
}
r.Header.Add(tknMap.Header, string(claimJson))
r.Header.Add(HeadersHeader, tknMap.Header)
}
}
} else {
return errors.New("invalid token")
}
return nil
}