-
Notifications
You must be signed in to change notification settings - Fork 46
/
parse_test.go
78 lines (68 loc) · 2.06 KB
/
parse_test.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
package jwt
import (
"strings"
"testing"
)
func TestParse(t *testing.T) {
testCases := []struct {
token string
header Header
claims string
signature string
}{
{
`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJqdXN0IGFuIGlkIiwiYXVkIjoiYXVkaWVuY2UifQ.t5oEdZGp0Qbth7lo5fZlV_o4-r9gMoYBSktXbarjWoo`,
Header{
Algorithm: HS256,
Type: "JWT",
},
`{"jti":"just an id","aud":"audience"}`,
"t5oEdZGp0Qbth7lo5fZlV_o4-r9gMoYBSktXbarjWoo",
},
{
`eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCIsImN0eSI6InRva2VuIn0.eyJqdGkiOiJqdXN0IGFuIGlkIiwiYXVkIjoiYXVkaWVuY2UifQ.t5oEdZGp0Qbth7lo5fZlV_o4-r9gMoYBSktXbarjWoo`,
Header{
Algorithm: HS512,
Type: "JWT",
ContentType: "token",
},
`{"jti":"just an id","aud":"audience"}`,
"t5oEdZGp0Qbth7lo5fZlV_o4-r9gMoYBSktXbarjWoo",
},
}
for _, tc := range testCases {
parts := strings.Split(tc.token, ".")
partHeader, _, _ := parts[0], parts[1], parts[2]
tk, err := Parse([]byte(tc.token), nopVerifier{})
mustOk(t, err)
mustEqual(t, string(tk.HeaderPart()), partHeader)
mustEqual(t, tk.Header(), tc.header)
mustEqual(t, string(tk.Claims()), tc.claims)
mustEqual(t, bytesToBase64(tk.Signature()), tc.signature)
}
}
func TestParseAnotherAlgorithm(t *testing.T) {
const tokenHS256 = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJqdXN0IGFuIGlkIiwiYXVkIjoiYXVkaWVuY2UifQ.t5oEdZGp0Qbth7lo5fZlV_o4-r9gMoYBSktXbarjWoo`
verifier := must(NewVerifierHS(HS512, []byte("key")))
_, err := Parse([]byte(tokenHS256), verifier)
mustEqual(t, err, ErrAlgorithmMismatch)
}
func TestParseMalformed(t *testing.T) {
testCases := []struct {
token string
}{
{`xyz.xyz`},
{`eyJ.xyz`},
{`eyJ!.x!yz.e30`},
{`eyJ.xyz.xyz`},
{`eyJhIjoxMjN9.x!yz.e30`}, // `e30` is JSON `{}` in base64.
{`eyJhIjoxMjN9.e30.x!yz`},
}
for _, tc := range testCases {
_, err := Parse([]byte(tc.token), nopVerifier{})
mustEqual(t, err, ErrInvalidFormat)
}
}
type nopVerifier struct{}
func (nopVerifier) Algorithm() Algorithm { return "nop" }
func (nopVerifier) Verify(token *Token) error { return nil }