-
Notifications
You must be signed in to change notification settings - Fork 23
/
token.go
55 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
package client
import (
"crypto/x509"
"encoding/pem"
"errors"
fmt "fmt"
jwt "github.com/dgrijalva/jwt-go"
"go.uber.org/zap"
)
func TokenWithClaims(bearer string, opts Options) (*jwt.Token, jwt.MapClaims, error) {
claims := jwt.MapClaims{}
// FIXME: add an option to automatically fetch the public key from
// https://id.pathwar.land/auth/realms/Pathwar-Dev/protocol/openid-connect/certs
// or
// https://id.pathwar.land/auth/realms/Pathwar-Dev
token, err := jwt.ParseWithClaims(bearer, claims, keyFunc(opts))
if err != nil {
if opts.Unsafe {
zap.L().Warn(
"invalid token",
zap.Error(err),
zap.Bool("client-unsafe", true),
)
parser := new(jwt.Parser)
token, _, err := parser.ParseUnverified(bearer, claims)
return token, claims, err
}
return nil, nil, err
}
return token, claims, nil
}
func keyFunc(opts Options) jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
key := []byte(fmt.Sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", opts.PublicKey))
pubPem, _ := pem.Decode(key)
if pubPem == nil {
return nil, errors.New("invalid pubkey")
}
parsedKey, err := x509.ParsePKIXPublicKey(pubPem.Bytes)
return parsedKey, err
}
}
func SubjectFromToken(token *jwt.Token) string {
mc := token.Claims.(jwt.MapClaims)
if v := mc["sub"]; v != nil {
return v.(string)
}
return ""
}