This repository has been archived by the owner on Mar 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoauth2_test.go
74 lines (60 loc) · 1.93 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, version 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package oauth2
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/hooklift/oauth2/types"
)
// getAccessTokenTest is a helper function to generate a valid grant and an access token.
func getAccessTokenTest(t *testing.T) (Provider, types.Token) {
cfg, authzCode := getTestAuthzCode(t)
provider := cfg.provider
req := AuthzGrantTokenRequestTest(t, "authorization_code", authzCode)
req.SetBasicAuth("testclient", "testclient")
w := httptest.NewRecorder()
IssueToken(w, req, cfg)
token := types.Token{}
err := json.Unmarshal(w.Body.Bytes(), &token)
ok(t, err)
return provider, token
}
// TestAuthzHandler tests that we are effectively able to protect server resources
// using AuthzHandler
func TestAuthzHandler(t *testing.T) {
mux := http.NewServeMux()
mux.Handle("/protected_resource", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("success!"))
}))
provider, token := getAccessTokenTest(t)
ts := httptest.NewServer(AuthzHandler(mux, provider))
defer ts.Close()
tests := []struct {
url string
token string
status int
body string
err string
}{
{ts.URL, "", http.StatusUnauthorized, "", "invalid_token"},
{ts.URL + "/protected_resource", token.Value, http.StatusOK, "success!", ""},
}
for _, tt := range tests {
req, err := http.NewRequest("GET", tt.url, nil)
ok(t, err)
req.Header.Set("Authorization", "Bearer "+tt.token)
res, err := http.DefaultClient.Do(req)
ok(t, err)
equals(t, tt.status, res.StatusCode)
oauth2Err := res.Header.Get("WWW-Authenticate")
equals(t, strings.Contains(oauth2Err, tt.err), true)
body, err := ioutil.ReadAll(res.Body)
ok(t, err)
equals(t, tt.body, string(body[:]))
}
}