-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvalidator_test.go
94 lines (83 loc) · 2.52 KB
/
validator_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
90
91
92
93
94
package oidc
import (
"github.com/golang-jwt/jwt/v4"
jwtRequest "github.com/golang-jwt/jwt/v4/request"
"github.com/golang-jwt/jwt/v4/test"
"io"
"net/http"
"net/http/httptest"
"testing"
)
var Authority = "http://kube-worker1:30692"
var Audience = "LSNG.Api"
var claims = jwt.MapClaims{
"iss": "http://kube-worker1:30692",
"aud": []string{
"http://kube-worker1:30692/resources",
"LSNG.Api",
"Notifier.Api",
},
"client_id": "CharismaFinancialServices",
"sub": "c8124881-ad67-443e-9473-08d5777d1ba8",
"idp": "local",
"partner_id": "-100",
"charisma_user_id": "1",
"scope": []string{
"openid",
"profile",
"roles",
"LSNG.Api.read_only",
"charisma_data",
"Notifier.Api.write",
},
"amr": []string{
"pwd",
},
}
func TestValidator(t *testing.T) {
privateKey := test.LoadRSAPrivateKeyFromDisk("./test/sample_key")
publicKey := test.LoadRSAPublicKeyFromDisk("./test/sample_key.pub")
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
tokenString, _ := token.SignedString(privateKey)
validator := NewJWTValidator(jwtRequest.OAuth2Extractor, NewKeyProvider(publicKey), Audience, Authority)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := validator(r)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
_, _ = io.WriteString(w, err.Error())
} else {
_, _ = io.WriteString(w, "OK")
}
})
req := httptest.NewRequest("GET", "/whatever", nil)
req.Header.Add("Authorization", "Bearer "+tokenString)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
result := w.Result()
if result.StatusCode != http.StatusOK {
t.Error("request failed status: ", result.StatusCode)
}
}
func BenchmarkTestValidator(b *testing.B) {
privateKey := test.LoadRSAPrivateKeyFromDisk("./test/sample_key")
publicKey := test.LoadRSAPublicKeyFromDisk("./test/sample_key.pub")
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
tokenString, _ := token.SignedString(privateKey)
validator := NewJWTValidator(jwtRequest.OAuth2Extractor, NewKeyProvider(publicKey), Audience, Authority)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := validator(r)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
_, _ = io.WriteString(w, err.Error())
} else {
_, _ = io.WriteString(w, "OK")
}
})
req := httptest.NewRequest("GET", "/whatever", nil)
req.Header.Add("Authorization", "Bearer "+tokenString)
w := httptest.NewRecorder()
for i := 0; i < b.N; i++ {
handler.ServeHTTP(w, req)
w.Result()
}
}