-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_auth.go
77 lines (66 loc) · 2.23 KB
/
client_auth.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
package jwtauth
import (
"crypto/rsa"
"fmt"
"github.com/golang-jwt/jwt"
"github.com/pkg/errors"
)
// ClientAuth represents client side authentication and authorization functionalities
type ClientAuth struct {
signingMethod jwt.SigningMethod
publicKey *rsa.PublicKey
publicKID string
}
// NewClientAuth create new ClientAuth
func NewClientAuth(alg string, publicKey *rsa.PublicKey, publicKID string) (*ClientAuth, error) {
if err := jwt.GetSigningMethod(alg); err == nil {
return nil, errors.New("invalid algorithm")
}
if publicKey == nil {
return nil, errors.New("pubKeyLookupFunc can not be nil")
}
cAuth := ClientAuth{
signingMethod: jwt.GetSigningMethod(alg),
publicKey: publicKey,
publicKID: publicKID,
}
return &cAuth, nil
}
// keyLookupFunction is used while validating token
func (c *ClientAuth) keyLookupFunction(token *jwt.Token) (interface{}, error) {
// if method in token supplied is not the method we're expecting, return error
if token.Method != c.signingMethod {
return nil, errors.New(fmt.Sprintf("Unexpected signing method: %v", token.Header["alg"]))
}
kid, ok := token.Header["kid"]
if !ok {
return nil, errors.New("kid not found in token")
}
if kid == c.publicKID {
return c.publicKey, nil
} else {
return nil, errors.New("publicKID does not match")
}
}
// Validate parse, and validate token. if successful it returns Claims recreated from token
func (c *ClientAuth) Validate(tokenStr string) (Claims, error) {
var claims Claims
token, err := jwt.ParseWithClaims(tokenStr, &claims, c.keyLookupFunction)
if err != nil {
return Claims{}, errors.Wrap(err, "parsing token with claims")
}
if token.Valid {
return claims, nil
} else if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return Claims{}, errors.New("token is not valid")
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
// Token is either expired or not active yet
return Claims{}, errors.New("token is either expired or not active yet")
} else {
return Claims{}, errors.New(fmt.Sprintf("Couldn't handle this token: %v", err))
}
} else {
return Claims{}, errors.New(fmt.Sprintf("Couldn't handle this token: %v", err))
}
}