forked from ory/hydra
/
client.go
124 lines (109 loc) · 3.96 KB
/
client.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package http
import (
"encoding/json"
"fmt"
"github.com/RangelReale/osin"
"github.com/go-errors/errors"
"github.com/ory-am/common/pkg"
. "github.com/ory-am/hydra/client"
"github.com/ory-am/hydra/middleware"
"github.com/parnurzeal/gorequest"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"net/http"
"net/url"
)
var isAllowed struct {
Allowed bool `json:"allowed"`
}
type HTTPClient struct {
ep string
clientToken *oauth2.Token
clientConfig *clientcredentials.Config
}
func New(endpoint, client, secret string) *HTTPClient {
return &HTTPClient{
ep: endpoint,
clientConfig: &clientcredentials.Config{
ClientSecret: secret,
ClientID: client,
TokenURL: pkg.JoinURL(endpoint, "oauth2/token"),
},
clientToken: &oauth2.Token{},
}
}
func (c *HTTPClient) SetClientToken(token *oauth2.Token) {
c.clientToken = token
}
func (c *HTTPClient) IsRequestAllowed(req *http.Request, resource, permission, owner string) (bool, error) {
var token *osin.BearerAuth
if token = osin.CheckBearerAuth(req); token == nil {
return false, errors.New("No token given.")
} else if token.Code == "" {
return false, errors.New("No token given.")
}
env := middleware.NewEnv(req)
env.Owner(owner)
return c.IsAllowed(&AuthorizeRequest{Token: token.Code, Resource: resource, Permission: permission, Context: env.Ctx()})
}
func (c *HTTPClient) IsAllowed(ar *AuthorizeRequest) (bool, error) {
return isValidAuthorizeRequest(c, ar, true)
}
func (c *HTTPClient) IsAuthenticated(token string) (bool, error) {
return isValidAuthenticationRequest(c, token, true)
}
func isValidAuthenticationRequest(c *HTTPClient, token string, retry bool) (bool, error) {
data := url.Values{}
data.Set("token", token)
request := gorequest.New()
resp, body, errs := request.Post(pkg.JoinURL(c.ep, "/oauth2/introspect")).Type("form").SetBasicAuth(c.clientConfig.ClientID, c.clientConfig.ClientSecret).SendString(data.Encode()).End()
if len(errs) > 0 {
return false, errors.Errorf("Got errors: %v", errs)
} else if resp.StatusCode != http.StatusOK {
return false, errors.Errorf("Status code %d is not 200: %s", resp.StatusCode, body)
}
if retry && resp.StatusCode == http.StatusUnauthorized {
var err error
if c.clientToken, err = c.clientConfig.Token(oauth2.NoContext); err != nil {
return false, errors.New(err)
} else if c.clientToken == nil {
return false, errors.New("Access token could not be retrieved")
}
return isValidAuthenticationRequest(c, token, false)
} else if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf("Status code %d is not 200", resp.StatusCode)
}
var introspect struct {
Active bool `json:"active"`
}
if err := json.Unmarshal([]byte(body), &introspect); err != nil {
return false, err
} else if !introspect.Active {
return false, errors.New("Authentication denied")
}
return introspect.Active, nil
}
func isValidAuthorizeRequest(c *HTTPClient, ar *AuthorizeRequest, retry bool) (bool, error) {
request := gorequest.New()
resp, body, errs := request.Post(pkg.JoinURL(c.ep, "/guard/allowed")).SetBasicAuth(c.clientConfig.ClientID, c.clientConfig.ClientSecret).Set("Content-Type", "application/json").Send(*ar).End()
if len(errs) > 0 {
return false, errors.Errorf("Got errors: %v", errs)
} else if retry && resp.StatusCode == http.StatusUnauthorized {
var err error
if c.clientToken, err = c.clientConfig.Token(oauth2.NoContext); err != nil {
return false, errors.New(err)
} else if c.clientToken == nil {
return false, errors.New("Access token could not be retrieved")
}
return isValidAuthorizeRequest(c, ar, false)
} else if resp.StatusCode != http.StatusOK {
return false, errors.Errorf("Status code %d is not 200: %s", resp.StatusCode, body)
}
if err := json.Unmarshal([]byte(body), &isAllowed); err != nil {
return false, errors.Errorf("Could not unmarshall body because %s", err.Error())
}
if !isAllowed.Allowed {
return false, errors.New("Authroization denied")
}
return isAllowed.Allowed, nil
}