forked from ory/keto
/
oauth2_introspection.go
193 lines (157 loc) · 5.74 KB
/
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/*
* Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @Copyright 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*
*/
package authentication
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
"net/url"
"fmt"
"github.com/ory/fosite"
"github.com/pkg/errors"
"golang.org/x/oauth2/clientcredentials"
)
// swagger:model authenticationOAuth2Session
type OAuth2Session struct {
// Subject is the identity that authorized issuing the token, for example a user or an OAuth2 app.
// This is usually a uuid but you can choose a urn or some other id too.
Subject string `json:"sub"`
// Allowed is true if the request is allowed and false otherwise.
Allowed bool `json:"allowed"`
// GrantedScopes is a list of scopes that the subject authorized when asked for consent.
GrantedScopes string `json:"scope"`
// Issuer is the id of the issuer, typically an hydra instance.
Issuer string `json:"iss"`
// ClientID is the id of the OAuth2 client that requested the token.
ClientID string `json:"client_id"`
// IssuedAt is the token creation time stamp.
IssuedAt time.Time `json:"iat"`
// ExpiresAt is the expiry timestamp.
ExpiresAt time.Time `json:"exp"`
NotBefore time.Time `json:"nbf,omitempty"`
Username string `json:"username,omitempty"`
Audience []string `json:"aud,omitempty"`
// Session represents arbitrary session data.
Extra map[string]interface{} `json:"session,omitempty"`
}
func (s *OAuth2Session) GrantAccess() {
s.Allowed = true
}
func (s *OAuth2Session) DenyAccess() {
s.Allowed = false
}
func (s *OAuth2Session) GetSubject() string {
return s.Subject
}
type IntrospectionResponse struct {
Active bool `json:"active"`
Scope string `json:"scope,omitempty"`
ClientID string `json:"client_id,omitempty"`
// Here, it's sub
Subject string `json:"sub,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Username string `json:"username,omitempty"`
Audience []string `json:"aud,omitempty"`
Issuer string `json:"iss,omitempty"`
TokenType string `json:"token_type,omitempty"`
// Session represents arbitrary session data.
Extra map[string]interface{} `json:"ext"`
}
type OAuth2IntrospectionAuthentication struct {
client *http.Client
introspectionURL string
scopeStrategy fosite.ScopeStrategy
}
// swagger:model AuthenticationOAuth2IntrospectionRequest
type AuthenticationOAuth2IntrospectionRequest struct {
// Token is the token to introspect.
Token string `json:"token"`
// Scope is an array of scopes that are required.
Scope []string `json:"scope"`
}
func NewOAuth2IntrospectionAuthentication(clientID, clientSecret, tokenURL, introspectionURL string, scopes []string, strategy fosite.ScopeStrategy) *OAuth2IntrospectionAuthentication {
c := clientcredentials.Config{
ClientID: clientID,
ClientSecret: clientSecret,
TokenURL: tokenURL,
Scopes: scopes,
}
return &OAuth2IntrospectionAuthentication{
client: c.Client(context.Background()),
introspectionURL: introspectionURL,
scopeStrategy: strategy,
}
}
func (a *OAuth2IntrospectionAuthentication) Authenticate(r *http.Request) (Session, error) {
var token AuthenticationOAuth2IntrospectionRequest
if err := json.NewDecoder(r.Body).Decode(&token); err != nil {
return nil, errors.WithStack(err)
}
ir, err := a.Introspect(token.Token, token.Scope, a.scopeStrategy)
if err != nil {
return nil, err
}
return &OAuth2Session{
Subject: ir.Subject,
GrantedScopes: ir.Scope,
ClientID: ir.ClientID,
ExpiresAt: time.Unix(ir.ExpiresAt, 0).UTC(),
IssuedAt: time.Unix(ir.IssuedAt, 0).UTC(),
NotBefore: time.Unix(ir.NotBefore, 0).UTC(),
Username: ir.Username,
Audience: ir.Audience,
Issuer: ir.Issuer,
Extra: ir.Extra,
}, nil
}
func (a *OAuth2IntrospectionAuthentication) Introspect(token string, scopes []string, strategy fosite.ScopeStrategy) (*IntrospectionResponse, error) {
body := url.Values{"token": {token}, "scope": {strings.Join(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)
}
var ir IntrospectionResponse
if err := json.NewDecoder(resp.Body).Decode(&ir); err != nil {
return nil, errors.WithStack(err)
}
if len(ir.TokenType) > 0 && ir.TokenType != "access_token" {
return nil, errors.WithStack(ErrUnauthorized.WithReason(fmt.Sprintf("Introspected token is not an access token but \"%s\"", ir.TokenType)))
}
if !ir.Active {
return nil, errors.WithStack(ErrUnauthorized.WithReason("Access token introspection says token is not active"))
}
if strategy != nil {
for _, scope := range scopes {
if !a.scopeStrategy(strings.Split(ir.Scope, " "), scope) {
return nil, errors.WithStack(ErrUnauthorized.WithReason(fmt.Sprintf("Scope %s was not granted", scope)))
}
}
}
return &ir, nil
}