-
Notifications
You must be signed in to change notification settings - Fork 6
/
oauth2_test.go
72 lines (62 loc) · 1.7 KB
/
oauth2_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
package main
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
)
func TestValidateJWTToken(t *testing.T) {
// Create a signer to generate test tokens
sharedKey := []byte("testkey")
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: sharedKey}, nil)
if err != nil {
t.Errorf("unable to create signer %s", err)
}
// Expired token
expiredCL := jwt.Claims{
Subject: "subject",
Issuer: "issuer",
Expiry: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)),
}
tok, err := jwt.Signed(signer).Claims(expiredCL).CompactSerialize()
if err != nil {
t.Fatalf("unable to creat jwt token %s", err)
}
err = validateJWTToken(tok)
expectedErr := fmt.Errorf("%v", jwt.ErrExpired)
if err == nil {
t.Fatal("Validation of expired token did not fail")
}
assert.Equal(t, err, expectedErr)
// Non expired token
activeCL := jwt.Claims{
Subject: "subject",
Issuer: "issuer",
Expiry: jwt.NewNumericDate(time.Now().Add(+1 * time.Minute)),
}
tok, err = jwt.Signed(signer).Claims(activeCL).CompactSerialize()
if err != nil {
t.Fatalf("unable to creat jwt token %s", err)
}
err = validateJWTToken(tok)
if err != nil {
t.Fatalf("Error validating token: %v", err)
}
// Missing exp field
missingExpCL := jwt.Claims{
Subject: "subject",
Issuer: "issuer",
}
tok, err = jwt.Signed(signer).Claims(missingExpCL).CompactSerialize()
if err != nil {
t.Fatalf("unable to creat jwt token %s", err)
}
err = validateJWTToken(tok)
expectedErr = fmt.Errorf("JWT token does not have exp field")
if err == nil {
t.Fatal("Validation of expired token did not fail")
}
assert.Equal(t, err, expectedErr)
}