-
Notifications
You must be signed in to change notification settings - Fork 492
/
oauth2.go
187 lines (163 loc) · 5.19 KB
/
oauth2.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
/*
* Copyright (c) 2017, MegaEase
* All rights reserved.
*
* 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.
*/
package validator
import (
"bytes"
"crypto/tls"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/golang-jwt/jwt"
"github.com/megaease/easegress/pkg/context"
)
type (
// OAuth2TokenIntrospect defines the validator configuration for OAuth2 token introspection
OAuth2TokenIntrospect struct {
EndPoint string `yaml:"endPoint" jsonschema:"required"`
BasicAuth string `yaml:"basicAuth" jsonschema:"omitempty"`
ClientID string `yaml:"clientId" jsonschema:"omitempty"`
ClientSecret string `yaml:"clientSecret" jsonschema:"omitempty"`
InsecureTLS bool `yaml:"insecureTls"`
}
// OAuth2JWT defines the validator configuration for OAuth2 self encoded access token
OAuth2JWT struct {
Algorithm string `yaml:"algorithm" jsonschema:"enum=HS256,enum=HS384,enum=HS512"`
// Secret is in hex encoding
Secret string `yaml:"secret" jsonschema:"required,pattern=^[A-Fa-f0-9]+$"`
secretBytes []byte
}
// OAuth2ValidatorSpec defines the configuration of OAuth2 validator
OAuth2ValidatorSpec struct {
TokenIntrospect *OAuth2TokenIntrospect `yaml:"tokenIntrospect" jsonschema:"omitempty"`
JWT *OAuth2JWT `yaml:"jwt" jsonschema:"omitempty"`
}
// OAuth2Validator defines the OAuth2 validator
OAuth2Validator struct {
spec *OAuth2ValidatorSpec
client *http.Client
}
tokenInfo struct {
Active bool `json:"active"`
Scope string `json:"scope"`
ClientID string `json:"client_id"`
UserName string `json:"username"`
TokenType string `json:"token_type"`
ExpiresAt int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
NotBefore int64 `json:"nbf"`
Subject string `json:"sub"`
Audience string `json:"aud"`
Issuer string `json:"iss"`
}
)
// NewOAuth2Validator creates a new OAuth2 validator
func NewOAuth2Validator(spec *OAuth2ValidatorSpec) *OAuth2Validator {
if spec.JWT != nil {
spec.JWT.secretBytes, _ = hex.DecodeString(spec.JWT.Secret)
}
v := &OAuth2Validator{spec: spec}
if spec.TokenIntrospect != nil {
if spec.TokenIntrospect.InsecureTLS {
cfg := tls.Config{InsecureSkipVerify: true}
v.client = &http.Client{Transport: &http.Transport{TLSClientConfig: &cfg}}
} else {
v.client = http.DefaultClient
}
}
return v
}
// make it mockable
var fnSendRequest = func(client *http.Client, r *http.Request) (*http.Response, error) {
return client.Do(r)
}
func (v *OAuth2Validator) introspectToken(tokenStr string) (*tokenInfo, error) {
var body bytes.Buffer
body.WriteString("token=")
body.WriteString(tokenStr)
if v.spec.TokenIntrospect.ClientID != "" {
body.WriteString("&client_id=")
body.WriteString(v.spec.TokenIntrospect.ClientID)
body.WriteString("&client_secret=")
body.WriteString(v.spec.TokenIntrospect.ClientSecret)
}
r, _ := http.NewRequest(http.MethodPost, v.spec.TokenIntrospect.EndPoint, &body)
if v.spec.TokenIntrospect.ClientID != "" {
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else if v.spec.TokenIntrospect.BasicAuth != "" {
r.Header.Set("Authorization", "Basic "+v.spec.TokenIntrospect.BasicAuth)
}
resp, e := fnSendRequest(v.client, r)
if e != nil {
return nil, e
}
var ti struct {
tokenInfo
Error string `json:"error"`
ErrorDesc string `json:"error_description"`
}
if e = json.NewDecoder(resp.Body).Decode(&ti); e != nil {
return nil, e
}
if ti.Error != "" {
return nil, fmt.Errorf("%s: %s", ti.Error, ti.ErrorDesc)
}
return &ti.tokenInfo, nil
}
// Validate validates the access token of a http request
func (v *OAuth2Validator) Validate(req context.HTTPRequest) error {
const prefix = "Bearer "
hdr := req.Header()
tokenStr := hdr.Get("Authorization")
if !strings.HasPrefix(tokenStr, prefix) {
return fmt.Errorf("unexpected authorization header: %s", tokenStr)
}
tokenStr = tokenStr[len(prefix):]
var subject, scope string
if v.spec.TokenIntrospect != nil {
ti, e := v.introspectToken(tokenStr)
if e != nil {
return e
}
if !ti.Active {
return fmt.Errorf("oauth2 authorization failed, token is inactive")
}
subject = ti.Subject
scope = ti.Scope
} else {
token, e := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
if alg := token.Method.Alg(); alg != v.spec.JWT.Algorithm {
return nil, fmt.Errorf("unexpected signing method: %v", alg)
}
return v.spec.JWT.secretBytes, nil
})
if e != nil {
return e
}
claims := token.Claims.(jwt.MapClaims)
subject, _ = claims["sub"].(string)
scope, _ = claims["scope"].(string)
}
if subject != "" {
hdr.Set("X-Authenticated-Userid", subject)
}
if scope != "" {
hdr.Set("X-Authenticated-Scope", scope)
}
return nil
}