-
Notifications
You must be signed in to change notification settings - Fork 0
/
openid.go
294 lines (244 loc) · 8.79 KB
/
openid.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package openid
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/RangelReale/osincli"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/util/sets"
authapi "github.com/openshift/origin/pkg/auth/api"
"github.com/openshift/origin/pkg/auth/oauth/external"
)
const (
// Standard claims (http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims)
SubjectClaim = "sub"
PreferredUsernameClaim = "preferred_username"
EmailClaim = "email"
NameClaim = "name"
)
type TokenValidator func(map[string]interface{}) error
type Config struct {
ClientID string
ClientSecret string
Scopes []string
ExtraAuthorizeParameters map[string]string
AuthorizeURL string
TokenURL string
UserInfoURL string
IDClaims []string
PreferredUsernameClaims []string
EmailClaims []string
NameClaims []string
IDTokenValidator TokenValidator
}
type provider struct {
providerName string
transport http.RoundTripper
Config
}
// NewProvider returns an implementation of an OpenID Connect Authorization Code Flow
// See http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth
// ID Token decryption is not supported
// UserInfo decryption is not supported
func NewProvider(providerName string, transport http.RoundTripper, config Config) (external.Provider, error) {
// TODO: Add support for discovery documents
// see http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig
// e.g. https://accounts.google.com/.well-known/openid-configuration
// Validate client id/secret
if len(config.ClientID) == 0 {
return nil, errors.New("ClientID is required")
}
if len(config.ClientSecret) == 0 {
return nil, errors.New("ClientSecret is required")
}
// Validate url presence
if len(config.AuthorizeURL) == 0 {
return nil, errors.New("Authorize URL is required")
} else if u, err := url.Parse(config.AuthorizeURL); err != nil {
return nil, errors.New("Authorize URL is invalid")
} else if u.Scheme != "https" {
return nil, errors.New("Authorize URL must use https scheme")
}
if len(config.TokenURL) == 0 {
return nil, errors.New("Token URL is required")
} else if u, err := url.Parse(config.TokenURL); err != nil {
return nil, errors.New("Token URL is invalid")
} else if u.Scheme != "https" {
return nil, errors.New("Token URL must use https scheme")
}
if len(config.UserInfoURL) > 0 {
if u, err := url.Parse(config.UserInfoURL); err != nil {
return nil, errors.New("UserInfo URL is invalid")
} else if u.Scheme != "https" {
return nil, errors.New("UserInfo URL must use https scheme")
}
}
if !sets.NewString(config.Scopes...).Has("openid") {
return nil, errors.New("Scopes must include openid")
}
if len(config.IDClaims) == 0 {
return nil, errors.New("IDClaims must specify at least one claim")
}
return provider{providerName, transport, config}, nil
}
// NewConfig implements external/interfaces/Provider.NewConfig
func (p provider) NewConfig() (*osincli.ClientConfig, error) {
config := &osincli.ClientConfig{
ClientId: p.ClientID,
ClientSecret: p.ClientSecret,
ErrorsInStatusCode: true,
SendClientSecretInParams: true,
AuthorizeUrl: p.AuthorizeURL,
TokenUrl: p.TokenURL,
Scope: strings.Join(p.Scopes, " "),
}
return config, nil
}
func (p provider) GetTransport() (http.RoundTripper, error) {
return p.transport, nil
}
// AddCustomParameters implements external/interfaces/Provider.AddCustomParameters
func (p provider) AddCustomParameters(req *osincli.AuthorizeRequest) {
for k, v := range p.ExtraAuthorizeParameters {
req.CustomParameters[k] = v
}
}
// GetUserIdentity implements external/interfaces/Provider.GetUserIdentity
func (p provider) GetUserIdentity(data *osincli.AccessData) (authapi.UserIdentityInfo, bool, error) {
// Token response MUST include id_token
// http://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
idToken, ok := data.ResponseData["id_token"].(string)
if !ok {
return nil, false, fmt.Errorf("No id_token returned in %v", data.ResponseData)
}
// id_token MUST be a valid JWT
idTokenClaims, err := decodeJWT(idToken)
if err != nil {
return nil, false, err
}
if p.IDTokenValidator != nil {
if err := p.IDTokenValidator(idTokenClaims); err != nil {
return nil, false, err
}
}
// TODO: validate JWT
// http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
// id_token MUST contain a sub claim as the subject identifier
// http://openid.net/specs/openid-connect-core-1_0.html#IDToken
idTokenSubject, ok := idTokenClaims[SubjectClaim].(string)
if !ok {
return nil, false, fmt.Errorf("id_token did not contain a 'sub' claim: %#v", idTokenClaims)
}
// Use id_token claims by default
claims := idTokenClaims
// If we have a userinfo URL, use it to get more detailed claims
if len(p.UserInfoURL) != 0 {
userInfoClaims, err := fetchUserInfo(p.UserInfoURL, data.AccessToken, p.transport)
if err != nil {
return nil, false, err
}
// The sub (subject) Claim MUST always be returned in the UserInfo Response.
// http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
userInfoSubject, ok := userInfoClaims[SubjectClaim].(string)
if !ok {
return nil, false, fmt.Errorf("userinfo response did not contain a 'sub' claim: %#v", userInfoClaims)
}
// The sub Claim in the UserInfo Response MUST be verified to exactly match the sub Claim in the ID Token;
// if they do not match, the UserInfo Response values MUST NOT be used.
// http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
if userInfoSubject != idTokenSubject {
return nil, false, fmt.Errorf("userinfo 'sub' claim (%s) did not match id_token 'sub' claim (%s)", userInfoSubject, idTokenSubject)
}
// Merge in userinfo claims in case id_token claims contained some that userinfo did not
for k, v := range userInfoClaims {
claims[k] = v
}
}
id, _ := getClaimValue(claims, p.IDClaims)
if id == "" {
return nil, false, fmt.Errorf("Could not retrieve id claim for %#v", p.IDClaims)
}
identity := authapi.NewDefaultUserIdentityInfo(p.providerName, id)
if preferredUsername, _ := getClaimValue(claims, p.PreferredUsernameClaims); len(preferredUsername) != 0 {
identity.Extra[authapi.IdentityPreferredUsernameKey] = preferredUsername
}
if email, _ := getClaimValue(claims, p.EmailClaims); len(email) != 0 {
identity.Extra[authapi.IdentityEmailKey] = email
}
if name, _ := getClaimValue(claims, p.NameClaims); len(name) != 0 {
identity.Extra[authapi.IdentityDisplayNameKey] = name
}
glog.V(4).Infof("identity=%v", identity)
return identity, true, nil
}
func getClaimValue(data map[string]interface{}, claims []string) (string, error) {
for _, claim := range claims {
value, ok := data[claim]
if !ok {
continue
}
stringValue, ok := value.(string)
if !ok {
return "", fmt.Errorf("Claim %s was not a string type", claim)
}
if len(stringValue) > 0 {
return stringValue, nil
}
}
return "", errors.New("No value found")
}
// fetch and decode JSON from the given UserInfo URL
func fetchUserInfo(url, accessToken string, transport http.RoundTripper) (map[string]interface{}, error) {
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
client := &http.Client{Transport: transport}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Non-200 response from UserInfo: %d, WWW-Authenticate=%s", resp.StatusCode, resp.Header.Get("WWW-Authenticate"))
}
// The UserInfo Claims MUST be returned as the members of a JSON object
// http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
decoded := map[string]interface{}{}
if err := json.Unmarshal(data, &decoded); err != nil {
return nil, err
}
return decoded, nil
}
// Decode JWT
// http://openid.net/specs/draft-jones-json-web-token-07.html
func decodeJWT(jwt string) (map[string]interface{}, error) {
jwtParts := strings.Split(jwt, ".")
if len(jwtParts) != 3 {
return nil, fmt.Errorf("Invalid JSON Web Token: expected 3 parts, got %d", len(jwtParts))
}
// Re-pad, if needed
encodedPayload := jwtParts[1]
if l := len(encodedPayload) % 4; l != 0 {
encodedPayload += strings.Repeat("=", 4-l)
}
// Decode base-64
decodedPayload, err := base64.StdEncoding.DecodeString(encodedPayload)
if err != nil {
return nil, fmt.Errorf("Error decoding payload: %v", err)
}
// Parse JSON
var data map[string]interface{}
err = json.Unmarshal([]byte(decodedPayload), &data)
if err != nil {
return nil, fmt.Errorf("Error parsing token: %v", err)
}
return data, nil
}