-
Notifications
You must be signed in to change notification settings - Fork 0
/
nojwt_test.go
84 lines (64 loc) · 1.73 KB
/
nojwt_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
79
80
81
82
83
84
package nojwt
import (
"bytes"
"testing"
)
var (
payload = []byte(`{"hello": "world!"}`)
secret = []byte("my secret")
)
const (
notAToken = "asdfasdfasdfasdf"
token = "eyJoZWxsbyI6ICJ3b3JsZCEifQ.g8o_EQ3pOt9qBQ-Yz8vK_rSoqWO47ds5hUsbPf9eObU"
tamperedSignature = "eyJoZWxsbyI6ICJ3b3JsZCEifQ.g8o_EQ3pOt9qBQ-xz8vK_rSoqWO47ds5hUsbPf9eObU"
tamperedPayload = "eyJoZWxxbyI6ICJ3b3JsZCEifQ.g8o_EQ3pOt9qBQ-xz8vK_rSoqWO47ds5hUsbPf9eObU"
)
func TestSign(t *testing.T) {
tok := SignHS256(payload, secret)
if token != tok {
t.Error("tokens don't match")
}
}
func TestParse(t *testing.T) {
payload2, err := Parse(tamperedSignature)
if !bytes.Equal(payload, payload2) {
t.Error("payloads don't match")
}
if err != nil {
t.Error("unable to parse token")
}
_, err = Parse(notAToken)
if err != ErrInvalidFormat {
t.Error("wrongly parsing wrong format")
}
}
func TestVerify(t *testing.T) {
payload2, err := VerifyHS256(token, secret)
if !bytes.Equal(payload, payload2) {
t.Error("payloads don't match")
}
if err == ErrInvalidFormat {
t.Error("unable to parse token")
}
if err == ErrInvalidSignature {
t.Error("unable to verify token")
}
payload2, err = VerifyHS256(tamperedSignature, secret)
if !bytes.Equal(payload, payload2) {
t.Error("payloads don't match")
}
if err != ErrInvalidSignature {
t.Error("wrongly verifying tampered signature token")
}
payload2, err = VerifyHS256(tamperedPayload, secret)
if bytes.Equal(payload, payload2) {
t.Error("payloads match on tampered payload")
}
if err != ErrInvalidSignature {
t.Error("wrongly verifying tampered signature token")
}
_, err = VerifyHS256(notAToken, secret)
if err != ErrInvalidFormat {
t.Error("wrongly parsing wrong format")
}
}