forked from oauth2-proxy/oauth2-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
azure.go
305 lines (260 loc) · 7.77 KB
/
azure.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
295
296
297
298
299
300
301
302
303
304
305
package providers
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
simplejson "github.com/bitly/go-simplejson"
"github.com/msepp/oauth2_proxy/v4/pkg/apis/sessions"
"github.com/msepp/oauth2_proxy/v4/pkg/logger"
"github.com/msepp/oauth2_proxy/v4/pkg/requests"
)
// AzureProvider represents an Azure based Identity Provider
type AzureProvider struct {
*ProviderData
Tenant string
}
// NewAzureProvider initiates a new AzureProvider
func NewAzureProvider(p *ProviderData) *AzureProvider {
p.ProviderName = "Azure"
if p.ProfileURL == nil || p.ProfileURL.String() == "" {
p.ProfileURL = &url.URL{
Scheme: "https",
Host: "graph.windows.net",
Path: "/me",
RawQuery: "api-version=1.6",
}
}
if p.ProtectedResource == nil || p.ProtectedResource.String() == "" {
p.ProtectedResource = &url.URL{
Scheme: "https",
Host: "graph.windows.net",
}
}
if p.Scope == "" {
p.Scope = "openid"
}
return &AzureProvider{ProviderData: p}
}
// Configure defaults the AzureProvider configuration options
func (p *AzureProvider) Configure(tenant string) {
p.Tenant = tenant
if tenant == "" {
p.Tenant = "common"
}
if p.LoginURL == nil || p.LoginURL.String() == "" {
p.LoginURL = &url.URL{
Scheme: "https",
Host: "login.microsoftonline.com",
Path: "/" + p.Tenant + "/oauth2/authorize"}
}
if p.RedeemURL == nil || p.RedeemURL.String() == "" {
p.RedeemURL = &url.URL{
Scheme: "https",
Host: "login.microsoftonline.com",
Path: "/" + p.Tenant + "/oauth2/token",
}
}
}
func getAzureHeader(accessToken string) http.Header {
header := make(http.Header)
header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
return header
}
func getEmailFromJSON(json *simplejson.Json) (string, error) {
var email string
var err error
email, err = json.Get("mail").String()
if err != nil || email == "" {
otherMails, otherMailsErr := json.Get("otherMails").Array()
if len(otherMails) > 0 {
email = otherMails[0].(string)
}
err = otherMailsErr
}
return email, err
}
// GetLoginURL with Azure specific OAuth2 parameters
func (p *AzureProvider) GetLoginURL(redirectURI, state string) string {
var a url.URL
a = *p.LoginURL
params, _ := url.ParseQuery(a.RawQuery)
params.Set("redirect_uri", redirectURI)
params.Add("scope", p.Scope)
params.Set("client_id", p.ClientID)
params.Set("response_type", "code")
params.Add("state", state)
if p.ApprovalPrompt != "" {
params.Set("prompt", p.ApprovalPrompt) // Azure uses "prompt" instead of "approval_prompt"
}
a.RawQuery = params.Encode()
return a.String()
}
// GetEmailAddress returns the Account email address
func (p *AzureProvider) GetEmailAddress(s *sessions.SessionState) (string, error) {
var email string
var err error
if s.AccessToken == "" {
return "", errors.New("missing access token")
}
req, err := http.NewRequest("GET", p.ProfileURL.String(), nil)
if err != nil {
return "", err
}
req.Header = getAzureHeader(s.AccessToken)
json, err := requests.Request(req)
if err != nil {
return "", err
}
email, err = getEmailFromJSON(json)
if err == nil && email != "" {
return email, err
}
email, err = json.Get("userPrincipalName").String()
if err != nil {
logger.Printf("failed making request %s", err)
return "", err
}
if email == "" {
logger.Printf("failed to get email address")
return "", err
}
return email, err
}
// Redeem an Azure OAuth2 token
func (p *AzureProvider) Redeem(redirectURL, code string) (s *sessions.SessionState, err error) {
if code == "" {
err = errors.New("missing code")
return
}
params := url.Values{}
params.Add("redirect_uri", redirectURL)
params.Add("client_id", p.ClientID)
params.Add("client_secret", p.ClientSecret)
params.Add("code", code)
params.Add("grant_type", "authorization_code")
if p.ProtectedResource != nil && p.ProtectedResource.String() != "" {
params.Add("resource", p.ProtectedResource.String())
}
var req *http.Request
req, err = http.NewRequest("POST", p.RedeemURL.String(), bytes.NewBufferString(params.Encode()))
if err != nil {
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
var resp *http.Response
resp, err = http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return
}
if resp.StatusCode != 200 {
err = fmt.Errorf("got %d from %q %s", resp.StatusCode, p.RedeemURL.String(), body)
return
}
// blindly try json and x-www-form-urlencoded
var jsonResponse struct {
ExpiresIn int64 `json:"expires_in,string"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
if err = json.Unmarshal(body, &jsonResponse); err != nil {
err = fmt.Errorf("decoding redeem response failed, %s", err)
return
}
s = &sessions.SessionState{
CreatedAt: time.Now(),
ExpiresOn: time.Now().Add(time.Duration(jsonResponse.ExpiresIn-300) * time.Second).Truncate(time.Second),
RefreshToken: jsonResponse.RefreshToken,
AccessToken: jsonResponse.AccessToken,
}
return
}
// RefreshSessionIfNeeded checks if the session has expired and uses the
// RefreshToken to fetch a new ID token if required
func (p *AzureProvider) RefreshSessionIfNeeded(s *sessions.SessionState) (bool, error) {
if s != nil {
log.Printf("RefreshSessionIfNeeded: refresh_token_len: %d, expires_on: %v, after: %t", len(s.RefreshToken), s.ExpiresOn, s.ExpiresOn.After(time.Now()))
} else {
log.Println("RefreshSessionIfNeeded: session is nil!")
}
if s == nil || s.ExpiresOn.After(time.Now()) || s.RefreshToken == "" {
log.Println("RefreshSessionIfNeeded: should not refresh!")
return false, nil
}
newSession, err := p.redeemRefreshToken(s.RefreshToken)
if err != nil {
logger.Printf("AZURE: redeem failed: %v", err)
return false, err
}
origExpiration := s.ExpiresOn
s.AccessToken = newSession.AccessToken
s.RefreshToken = newSession.RefreshToken
s.Email = newSession.Email
s.CreatedAt = newSession.CreatedAt
s.ExpiresOn = newSession.ExpiresOn
logger.Printf("AZURE: refreshed access token (expired on %s, next: %s)", origExpiration, s.ExpiresOn)
return true, nil
}
func (p *AzureProvider) redeemRefreshToken(refreshToken string) (*sessions.SessionState, error) {
// https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code
params := url.Values{}
params.Add("client_id", p.ClientID)
params.Add("client_secret", p.ClientSecret)
params.Add("refresh_token", refreshToken)
params.Add("grant_type", "refresh_token")
params.Add("resource", p.ProtectedResource.String())
var (
req *http.Request
err error
)
req, err = http.NewRequest("POST", p.RedeemURL.String(), bytes.NewBufferString(params.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
err = fmt.Errorf("got %d from %q %s", resp.StatusCode, p.RedeemURL.String(), body)
return nil, err
}
var data struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int64 `json:"expires_in,string"`
}
err = json.Unmarshal(body, &data)
if err != nil {
return nil, err
}
var s = &sessions.SessionState{
AccessToken: data.AccessToken,
RefreshToken: data.RefreshToken,
ExpiresOn: time.Now().Add(time.Duration(data.ExpiresIn-300) * time.Second).Truncate(time.Second),
CreatedAt: time.Now(),
}
log.Printf("refresh_token len: %d, expires_on: %v", len(s.RefreshToken), s.ExpiresOn)
if s.Email, err = p.GetEmailAddress(s); err != nil {
return nil, err
}
return s, nil
}