-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
oauth2_test.go
76 lines (63 loc) · 1.59 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
73
74
75
76
package examples
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gavv/httpexpect/v2"
"golang.org/x/oauth2"
)
var (
AccessToken = "xxx"
RefreshToken = "yyy"
)
func TestOAuth2(t *testing.T) {
server := httptest.NewServer(OAuth2Handler())
defer server.Close()
config := oauth2.Config{
ClientID: ClientID,
ClientSecret: ClientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: server.URL + "/token",
},
}
token := &oauth2.Token{
AccessToken: AccessToken,
RefreshToken: RefreshToken,
Expiry: time.Now().Add(5 * time.Minute),
}
client := config.Client(context.Background(), token)
e := httpexpect.WithConfig(httpexpect.Config{
BaseURL: server.URL,
Client: client,
Reporter: httpexpect.NewAssertReporter(t),
Printers: []httpexpect.Printer{
httpexpect.NewDebugPrinter(t, true),
},
})
e.GET("/protected").
Expect().
Status(http.StatusBadRequest)
tokenResp := e.GET("/token").
WithQueryObject(map[string]interface{}{
"grant_type": "client_credentials",
"client_id": ClientID,
"client_secret": ClientSecret,
"scope": "all",
}).
Expect()
tokenResp.Status(http.StatusOK)
tokenResp.JSON().Path("$.scope").String().IsEqual("all")
tokenResp.JSON().Path("$.token_type").String().IsEqual("Bearer")
tokenResp.JSON().Path("$.expires_in").Number().Gt(0)
accessToken := tokenResp.JSON().Path("$.access_token").String().Raw()
if token.AccessToken != accessToken {
token.AccessToken = accessToken
}
e.GET("/protected").
Expect().
Status(http.StatusOK).
Body().
IsEqual("protected_content")
}