-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokengenerator_test.go
89 lines (68 loc) · 2.02 KB
/
tokengenerator_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
85
86
87
88
89
package auth
import (
"crypto/rand"
"crypto/rsa"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
func TestTokenGenerator(t *testing.T) {
if !testing.Verbose() {
t.Parallel()
}
Convey("Given a token generator method with a random secret", t, func() {
secret := make([]byte, 50)
rand.Read(secret)
method := SigningMethodHMAC(secret, Size512)
generator := NewTokenGenerator(method)
Convey("When a token is signed", func() {
token := generator.Create()
token.Claims["foo"] = "bar"
str, err := generator.Sign(token)
So(err, ShouldBeNil)
Convey("Then the token should be valid", func() {
parsed, err := generator.Verify(str)
So(err, ShouldBeNil)
So(parsed.Claims["foo"], ShouldEqual, "bar")
})
})
Convey("When an expired token is signed", func() {
token := generator.Create()
token.Claims["exp"] = time.Now().Add(-time.Hour).Unix()
token.Claims["foo"] = "bar"
str, err := generator.Sign(token)
So(err, ShouldBeNil)
Convey("Then the token should be invalid", func() {
parsed, err := generator.Verify(str)
So(parsed, ShouldBeNil)
So(err, ShouldNotBeNil)
})
})
Convey("When an invalid token is verified", func() {
parsed, err := generator.Verify("invalid_token")
Convey("Then an error should be returned", func() {
So(parsed, ShouldBeNil)
So(err, ShouldNotBeNil)
})
})
Convey("When an token with an invalid alg is verified", func() {
key, err := rsa.GenerateKey(rand.Reader, 1024)
So(err, ShouldBeNil)
keygen := SimpleRSAKeyGen(key)
methodRSA := SigningMethodRSAPSS(keygen, Size256)
generatorRSA := NewTokenGenerator(methodRSA)
token := generatorRSA.Create()
str, err := generatorRSA.Sign(token)
So(err, ShouldBeNil)
Convey("Then an error should be returned", func() {
parsed, err := generator.Verify(str)
So(parsed, ShouldBeNil)
So(err, ShouldNotBeNil)
})
})
})
}
func NewMockTokenGenerator() *TokenGenerator {
method := NewMockSigningMethod()
return NewTokenGenerator(method)
}