-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathARMOAuthModule.cs
402 lines (342 loc) · 14 KB
/
ARMOAuthModule.cs
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IdentityModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Services;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Web;
namespace ARMOAuth.Modules
{
public class ARMOAuthModule : IHttpModule
{
public const string ManagementResource = "https://management.core.windows.net/";
public const string TenantIdClaimType = "http://schemas.microsoft.com/identity/claims/tenantid";
public const string NonceClaimType = "nonce";
public const string OAuthTokenCookie = "OAuthToken";
public const string DeleteCookieFormat = "{0}=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
public const int CookieChunkSize = 2000;
public static readonly CookieTransform[] DefaultCookieTransforms = new CookieTransform[]
{
new DeflateCookieTransform(),
new MachineKeyTransform()
};
public static string AADClientId
{
get { return ConfigurationManager.AppSettings["AADClientId"]; }
}
public static string AADClientSecret
{
get { return ConfigurationManager.AppSettings["AADClientSecret"]; }
}
public bool Enabled
{
get { return !String.IsNullOrEmpty(AADClientId) && !String.IsNullOrEmpty(AADClientSecret); }
}
public void Dispose()
{
}
public void Init(HttpApplication context)
{
if (Enabled)
{
context.AuthenticateRequest += AuthenticateRequest;
}
}
public void AuthenticateRequest(object sender, EventArgs e)
{
ClaimsPrincipal principal = null;
var application = (HttpApplication)sender;
var request = application.Request;
var response = application.Response;
if (request.Url.Scheme != "https")
{
response.Redirect(String.Format("https://{0}{1}", request.Url.Authority, request.Url.PathAndQuery), endResponse: true);
return;
}
if (request.Url.PathAndQuery.StartsWith("/logout", StringComparison.OrdinalIgnoreCase))
{
RemoveSessionCookie(application);
var logoutUrl = GetLogoutUrl(application);
response.Redirect(logoutUrl, endResponse: true);
return;
}
string tenantId;
if (SwitchTenant(application, out tenantId))
{
RemoveSessionCookie(application);
var loginUrl = GetLoginUrl(application, tenantId, "/token");
response.Redirect(loginUrl, endResponse: true);
return;
}
var id_token = request.Form["id_token"];
var code = request.Form["code"];
var state = request.Form["state"];
if (!String.IsNullOrEmpty(id_token) && !String.IsNullOrEmpty(code))
{
principal = AuthenticateIdToken(application, id_token);
var tenantIdClaim = principal.Claims.FirstOrDefault(c => c.Type == TenantIdClaimType);
if (tenantIdClaim == null)
{
throw new InvalidOperationException("Missing tenantid claim");
}
var redirect_uri = request.Url.GetLeftPart(UriPartial.Authority);
var token = AADOAuth2AccessToken.GetAccessTokenByCode(tenantIdClaim.Value, code, redirect_uri);
WriteOAuthTokenCookie(application, token);
response.Redirect(redirect_uri + state, endResponse: true);
return;
}
else
{
var token = ReadOAuthTokenCookie(application);
if (token != null)
{
if (!token.IsValid())
{
token = AADOAuth2AccessToken.GetAccessTokenByRefreshToken(token.TenantId, token.refresh_token, ManagementResource);
WriteOAuthTokenCookie(application, token);
}
principal = new ClaimsPrincipal(new ClaimsIdentity("AAD"));
request.ServerVariables["HTTP_X_MS_OAUTH_TOKEN"] = token.access_token;
}
}
if (principal == null)
{
var loginUrl = GetLoginUrl(application);
response.Redirect(loginUrl, endResponse: true);
return;
}
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
}
public static string GetLoginUrl(HttpApplication application, string tenantId = null, string state = null)
{
const string scope = "user_impersonation openid";
const string site_id = "500879";
var config = OpenIdConfiguration.Current;
var request = application.Context.Request;
var response_type = "id_token code";
var issuerAddress = config.GetAuthorizationEndpoint(tenantId);
var redirect_uri = request.Url.GetLeftPart(UriPartial.Authority);
var client_id = AADClientId;
var nonce = GenerateNonce();
var response_mode = "form_post";
StringBuilder strb = new StringBuilder();
strb.Append(issuerAddress);
strb.AppendFormat("?response_type={0}", WebUtility.UrlEncode(response_type));
strb.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(redirect_uri));
strb.AppendFormat("&client_id={0}", WebUtility.UrlEncode(client_id));
strb.AppendFormat("&resource={0}", WebUtility.UrlEncode(ManagementResource));
strb.AppendFormat("&scope={0}", WebUtility.UrlEncode(scope));
strb.AppendFormat("&nonce={0}", WebUtility.UrlEncode(nonce));
strb.AppendFormat("&site_id={0}", WebUtility.UrlEncode(site_id));
strb.AppendFormat("&response_mode={0}", WebUtility.UrlEncode(response_mode));
strb.AppendFormat("&state={0}", WebUtility.UrlEncode(state ?? request.Url.PathAndQuery));
return strb.ToString();
}
public static string GetLogoutUrl(HttpApplication application)
{
var config = OpenIdConfiguration.Current;
var request = application.Context.Request;
//var redirect_uri = new Uri(request.Url, LogoutComplete);
StringBuilder strb = new StringBuilder();
strb.Append(config.EndSessionEndpoint);
//strb.AppendFormat("?post_logout_redirect_uri={0}", WebUtility.UrlEncode(redirect_uri.AbsoluteUri));
return strb.ToString();
}
public static ClaimsPrincipal AuthenticateIdToken(HttpApplication application, string id_token)
{
var config = OpenIdConfiguration.Current;
var handler = new JwtSecurityTokenHandler();
handler.CertificateValidator = X509CertificateValidator.None;
if (!handler.CanReadToken(id_token))
{
throw new InvalidOperationException("No SecurityTokenHandler can authenticate this id_token!");
}
var parameters = new TokenValidationParameters();
parameters.AllowedAudience = AADClientId;
// this is just for Saml
// paramaters.AudienceUriMode = AudienceUriMode.Always;
parameters.ValidateIssuer = false;
var tokens = new List<SecurityToken>();
foreach (var key in config.IssuerKeys.Keys)
{
tokens.AddRange(key.GetSecurityTokens());
}
parameters.SigningTokens = tokens;
// validate
var principal = (ClaimsPrincipal)handler.ValidateToken(id_token, parameters);
// verify nonce
VerifyNonce(principal.FindFirst(NonceClaimType).Value);
return principal;
}
public static bool SwitchTenant(HttpApplication application, out string tenantId)
{
tenantId = null;
var request = application.Request;
if (request.Url.PathAndQuery.StartsWith("/tenants", StringComparison.OrdinalIgnoreCase))
{
var parts = request.Url.PathAndQuery.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2)
{
tenantId = parts[1];
}
}
return tenantId != null;
}
public static byte[] EncodeCookie(AADOAuth2AccessToken token)
{
var bytes = token.ToBytes();
for (int i = 0; i < DefaultCookieTransforms.Length; ++i)
{
bytes = DefaultCookieTransforms[i].Encode(bytes);
}
return bytes;
}
public static AADOAuth2AccessToken DecodeCookie(byte[] bytes)
{
try
{
for (int i = DefaultCookieTransforms.Length - 1; i >= 0; --i)
{
bytes = DefaultCookieTransforms[i].Decode(bytes);
}
return AADOAuth2AccessToken.FromBytes(bytes);
}
catch (Exception)
{
// bad cookie
return null;
}
}
// NOTE: generate nonce
public static string GenerateNonce()
{
return Guid.NewGuid().ToString();
}
// NOTE: verify nonce
public static void VerifyNonce(string nonce)
{
}
public static AADOAuth2AccessToken ReadOAuthTokenCookie(HttpApplication application)
{
var request = application.Context.Request;
// read oauthtoken cookie
var cookies = request.Cookies;
var strb = new StringBuilder();
int index = 0;
while (true)
{
var cookieName = OAuthTokenCookie;
if (index > 0)
{
cookieName += index.ToString(CultureInfo.InvariantCulture);
}
var cookie = cookies[cookieName];
if (cookie == null)
{
break;
}
strb.Append(cookie.Value);
++index;
}
if (strb.Length == 0)
{
return null;
}
var bytes = Convert.FromBase64String(strb.ToString());
var oauthToken = DecodeCookie(bytes);
if (oauthToken == null || !oauthToken.IsValid())
{
try
{
if (oauthToken != null)
{
oauthToken = AADOAuth2AccessToken.GetAccessTokenByRefreshToken(oauthToken.TenantId, oauthToken.refresh_token, oauthToken.resource);
}
}
catch (Exception)
{
oauthToken = null;
}
if (oauthToken == null)
{
RemoveSessionCookie(application);
return null;
}
WriteOAuthTokenCookie(application, oauthToken);
}
return oauthToken;
}
public static void WriteOAuthTokenCookie(HttpApplication application, AADOAuth2AccessToken oauthToken)
{
var request = application.Context.Request;
var response = application.Context.Response;
var bytes = EncodeCookie(oauthToken);
var cookie = Convert.ToBase64String(bytes);
var chunkCount = cookie.Length / CookieChunkSize + (cookie.Length % CookieChunkSize == 0 ? 0 : 1);
for (int i = 0; i < chunkCount; ++i)
{
var setCookie = new StringBuilder();
setCookie.Append(OAuthTokenCookie);
if (i > 0)
{
setCookie.Append(i.ToString(CultureInfo.InvariantCulture));
}
setCookie.Append('=');
int startIndex = i * CookieChunkSize;
setCookie.Append(cookie.Substring(startIndex, Math.Min(CookieChunkSize, cookie.Length - startIndex)));
setCookie.Append("; path=/; secure; HttpOnly");
response.Headers.Add("Set-Cookie", setCookie.ToString());
}
var cookies = request.Cookies;
var index = chunkCount;
while (true)
{
var cookieName = OAuthTokenCookie;
if (index > 0)
{
cookieName += index.ToString(CultureInfo.InvariantCulture);
}
if (cookies[cookieName] == null)
{
break;
}
// remove old cookie
response.Headers.Add("Set-Cookie", String.Format(DeleteCookieFormat, cookieName));
++index;
}
}
public static void RemoveSessionCookie(HttpApplication application)
{
var request = application.Context.Request;
var response = application.Context.Response;
var cookies = request.Cookies;
foreach (string name in new[] { OAuthTokenCookie })
{
int index = 0;
while (true)
{
string cookieName = name;
if (index > 0)
{
cookieName += index.ToString(CultureInfo.InvariantCulture);
}
if (cookies[cookieName] == null)
{
break;
}
// remove old cookie
response.Headers.Add("Set-Cookie", String.Format(DeleteCookieFormat, cookieName));
++index;
}
}
}
}
}