-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathjwt.go
69 lines (56 loc) · 1.81 KB
/
jwt.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
package jsonpath
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"net/http"
"strings"
"github.com/steinfletcher/apitest-jsonpath/jsonpath"
)
const (
jwtHeaderIndex = 0
jwtPayloadIndex = 1
)
func JWTHeaderEqual(tokenSelector func(*http.Response) (string, error), expression string, expected interface{}) func(*http.Response, *http.Request) error {
return jwtEqual(tokenSelector, expression, expected, jwtHeaderIndex)
}
func JWTPayloadEqual(tokenSelector func(*http.Response) (string, error), expression string, expected interface{}) func(*http.Response, *http.Request) error {
return jwtEqual(tokenSelector, expression, expected, jwtPayloadIndex)
}
func jwtEqual(tokenSelector func(*http.Response) (string, error), expression string, expected interface{}, index int) func(*http.Response, *http.Request) error {
return func(response *http.Response, request *http.Request) error {
token, err := tokenSelector(response)
if err != nil {
return err
}
parts := strings.Split(token, ".")
if len(parts) != 3 {
splitErr := errors.New("invalid token: token should contain header, payload and secret")
return splitErr
}
decodedPayload, PayloadErr := base64Decode(parts[index])
if PayloadErr != nil {
return fmt.Errorf("invalid jwt: %s", PayloadErr.Error())
}
value, err := jsonpath.JsonPath(bytes.NewReader(decodedPayload), expression)
if err != nil {
return err
}
if !jsonpath.ObjectsAreEqual(value, expected) {
return errors.New(fmt.Sprintf("\"%s\" not equal to \"%s\"", value, expected))
}
return nil
}
}
func base64Decode(src string) ([]byte, error) {
if l := len(src) % 4; l > 0 {
src += strings.Repeat("=", 4-l)
}
decoded, err := base64.URLEncoding.DecodeString(src)
if err != nil {
errMsg := fmt.Errorf("decoding Error %s", err)
return nil, errMsg
}
return decoded, nil
}