-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinternal.go
81 lines (66 loc) · 2.31 KB
/
internal.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
// Package gojwtcognito is an easy to use, small package designed to parse request headers and look for
// JWTs provided by AWS Cognito to either check if they are valid or get some data from them.
package gojwtcognito
import (
"encoding/json"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/lestrrat-go/jwx/jwk"
"net/http"
"strings"
)
// fetches from the request header all the necessary info to get the cookie info
func getCookie(request *http.Request, appClient string, tokenType string) (*http.Cookie, error) {
userIdCookie := fmt.Sprintf("CognitoIdentityServiceProvider.%v.LastAuthUser", appClient)
userId, err := request.Cookie(userIdCookie)
if err != nil {
return nil, fmt.Errorf("could not find cookie with name: %v", userIdCookie)
}
tokenName := fmt.Sprintf("CognitoIdentityServiceProvider.%v.%v.%v", appClient, userId.Value, tokenType)
cookie, err := request.Cookie(tokenName)
if err != nil {
return nil, fmt.Errorf("could not find cookie with name: %v", tokenName)
}
return cookie, nil
}
// segment is used to unmarshall a part of cookie
type segment struct {
Kid string `json:"kid"`
}
// getKey builds the key using the jwks and the first part of the specified cookie in order to match key ids
func getKey(cookie *http.Cookie, jwks *jwk.Set) (interface{}, error) {
// the key id of a JWT is in the first part of the value
tokenIdSegment := strings.Split(cookie.Value, ".")[0]
decodedIdSegment, err := jwt.DecodeSegment(tokenIdSegment)
if err != nil {
return nil, err
}
var seg segment
err = json.Unmarshal(decodedIdSegment, &seg)
if err != nil {
return nil, err
}
// matches key id from the cookie and the jwks
keys := jwks.LookupKeyID(seg.Kid)
if len(keys) == 0 {
return nil, fmt.Errorf("failed to look up: %v", seg.Kid)
}
key, err := keys[0].Materialize()
if err != nil {
return nil, err
}
return key, nil
}
// parses a JWT using the cookie where it is contained and the key obtained from getKey() and returns it.
func getToken(cookie *http.Cookie, key interface{}) (*jwt.Token, error) {
token, err := jwt.Parse(cookie.Value, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return key, nil
})
if err != nil {
return nil, err
}
return token, nil
}