-
-
Notifications
You must be signed in to change notification settings - Fork 348
/
authenticator_oauth2_introspection.go
165 lines (137 loc) · 5.65 KB
/
authenticator_oauth2_introspection.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package proxy
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/pkg/errors"
"golang.org/x/oauth2/clientcredentials"
"github.com/ory/fosite"
"github.com/ory/go-convenience/stringslice"
"github.com/ory/oathkeeper/helper"
"github.com/ory/oathkeeper/rule"
)
type AuthenticatorOAuth2IntrospectionConfiguration struct {
// An array of OAuth 2.0 scopes that are required when accessing an endpoint protected by this handler.
// If the token used in the Authorization header did not request that specific scope, the request is denied.
Scopes []string `json:"required_scope"`
// An array of audiences that are required when accessing an endpoint protected by this handler.
// If the token used in the Authorization header is not intended for any of the requested audiences, the request is denied.
Audience []string `json:"target_audience"`
// The token must have been issued by one of the issuers listed in this array.
Issuers []string `json:"trusted_issuers"`
}
type AuthenticatorOAuth2Introspection struct {
client *http.Client
introspectionURL string
scopeStrategy fosite.ScopeStrategy
}
func NewAuthenticatorOAuth2Introspection(
clientID, clientSecret, tokenURL, introspectionURL string,
scopes []string, strategy fosite.ScopeStrategy,
) (*AuthenticatorOAuth2Introspection, error) {
if _, err := url.ParseRequestURI(introspectionURL); err != nil {
return new(AuthenticatorOAuth2Introspection), errors.Errorf(`unable to validate the OAuth 2.0 Introspection Authenticator's Token Introspection URL "%s" because %s`, introspectionURL, err)
}
c := http.DefaultClient
if len(clientID)+len(clientSecret)+len(tokenURL)+len(scopes) > 0 {
if len(clientID) == 0 {
return new(AuthenticatorOAuth2Introspection), errors.Errorf("if OAuth 2.0 Authorization is used in the OAuth 2.0 Introspection Authenticator, the OAuth 2.0 Client ID must be set but was not")
}
if len(clientSecret) == 0 {
return new(AuthenticatorOAuth2Introspection), errors.Errorf("if OAuth 2.0 Authorization is used in the OAuth 2.0 Introspection Authenticator, the OAuth 2.0 Client ID must be set but was not")
}
if _, err := url.ParseRequestURI(tokenURL); err != nil {
return new(AuthenticatorOAuth2Introspection), errors.Errorf(`if OAuth 2.0 Authorization is used in the OAuth 2.0 Introspection Authenticator, the OAuth 2.0 Token URL must be set but validating URL "%s" failed because %s`, tokenURL, err)
}
c = (&clientcredentials.Config{
ClientID: clientID,
ClientSecret: clientSecret,
TokenURL: tokenURL,
Scopes: scopes,
}).Client(context.Background())
}
return &AuthenticatorOAuth2Introspection{
client: c,
introspectionURL: introspectionURL,
scopeStrategy: strategy,
}, nil
}
func (a *AuthenticatorOAuth2Introspection) GetID() string {
return "oauth2_introspection"
}
type introspection struct {
Active bool `json:"active"`
Extra map[string]interface{} `json:"ext"`
Subject string `json:"sub,omitempty"`
Username string `json:"username"`
Audience []string `json:"aud"`
TokenType string `json:"token_type"`
Issuer string `json:"iss"`
ClientID string `json:"client_id,omitempty"`
Scope string `json:"scope,omitempty"`
}
func (a *AuthenticatorOAuth2Introspection) Authenticate(r *http.Request, config json.RawMessage, rl *rule.Rule) (*AuthenticationSession, error) {
var i introspection
var cf AuthenticatorOAuth2IntrospectionConfiguration
if len(config) == 0 {
config = []byte("{}")
}
d := json.NewDecoder(bytes.NewBuffer(config))
d.DisallowUnknownFields()
if err := d.Decode(&cf); err != nil {
return nil, errors.WithStack(err)
}
token := helper.BearerTokenFromRequest(r)
if token == "" {
return nil, errors.WithStack(ErrAuthenticatorNotResponsible)
}
body := url.Values{"token": {token}, "scope": {strings.Join(cf.Scopes, " ")}}
resp, err := a.client.Post(a.introspectionURL, "application/x-www-form-urlencoded", strings.NewReader(body.Encode()))
if err != nil {
return nil, errors.WithStack(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("Introspection returned status code %d but expected %d", resp.StatusCode, http.StatusOK)
}
if err := json.NewDecoder(resp.Body).Decode(&i); err != nil {
return nil, errors.WithStack(err)
}
if len(i.TokenType) > 0 && i.TokenType != "access_token" {
return nil, errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf("Introspected token is not an access token but \"%s\"", i.TokenType)))
}
if !i.Active {
return nil, errors.WithStack(helper.ErrForbidden.WithReason("Access token i says token is not active"))
}
for _, audience := range cf.Audience {
if !stringslice.Has(i.Audience, audience) {
return nil, errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf("Token audience is not intended for target audience %s", audience)))
}
}
if len(cf.Issuers) > 0 {
if !stringslice.Has(cf.Issuers, i.Issuer) {
return nil, errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf("Token issuer does not match any trusted issuer")))
}
}
if a.scopeStrategy != nil {
for _, scope := range cf.Scopes {
if !a.scopeStrategy(strings.Split(i.Scope, " "), scope) {
return nil, errors.WithStack(helper.ErrForbidden.WithReason(fmt.Sprintf("Scope %s was not granted", scope)))
}
}
}
if len(i.Extra) == 0 {
i.Extra = map[string]interface{}{}
}
i.Extra["username"] = i.Username
i.Extra["client_id"] = i.ClientID
i.Extra["scope"] = i.Scope
return &AuthenticationSession{
Subject: i.Subject,
Extra: i.Extra,
}, nil
}