-
Notifications
You must be signed in to change notification settings - Fork 2
/
Auth0Module.cs
399 lines (337 loc) · 13.7 KB
/
Auth0Module.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
using System;
using System.Configuration;
using System.Globalization;
using System.IdentityModel;
using System.IdentityModel.Services;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
namespace Auth0Module
{
// spec: https://docs.auth0.com/protocols
public class Auth0Module : IHttpModule
{
public const string LiveAuth = "Auth0OAuth";
public const string DeleteCookieFormat = "{0}=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
public const int CookieChunkSize = 2000;
public const string LoginCallbackPath = "/login/callback";
public const string LogoutPath = "/logout";
public const string LogoutCompletePath = "/logout/complete";
public static readonly CookieTransform[] DefaultCookieTransforms = new CookieTransform[]
{
new DeflateCookieTransform(),
new MachineKeyTransform()
};
public static string Auth0ClientId
{
get { return ConfigurationManager.AppSettings["Auth0ClientId"]; }
}
public static string Auth0ClientSecret
{
get { return ConfigurationManager.AppSettings["Auth0ClientSecret"]; }
}
public static string Auth0Domain
{
get { return ConfigurationManager.AppSettings["Auth0Domain"]; }
}
public bool Enabled
{
get { return !String.IsNullOrEmpty(Auth0ClientId) && !String.IsNullOrEmpty(Auth0ClientSecret) && !String.IsNullOrEmpty(Auth0Domain); }
}
public void Init(HttpApplication context)
{
// disable the feature if configuration is not defined
if (Enabled)
{
context.AuthenticateRequest += AuthenticateRequest;
}
}
public void Dispose()
{
}
public void AuthenticateRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var request = application.Request;
var requestUrl = new Uri(request.Url, request.RawUrl);
var response = application.Response;
Auth0Trace.WriteLine("request = {0}", requestUrl);
if (requestUrl.AbsolutePath.StartsWith(LogoutPath, StringComparison.OrdinalIgnoreCase))
{
if (requestUrl.AbsolutePath.Equals(LogoutPath, StringComparison.OrdinalIgnoreCase))
{
RemoveSessionCookie(application);
response.Redirect(GetLogoutUrl(application), endResponse: true);
}
else
{
response.Write("<a href=\"/\">login</a>");
application.CompleteRequest();
}
return;
}
string redirectUri;
var token = AuthenticateUser(application, out redirectUri);
if (token == null)
{
redirectUri = redirectUri ?? GetLoginUrl(application);
}
if (!String.IsNullOrEmpty(redirectUri))
{
Auth0Trace.WriteLine("redirectUri = {0}", redirectUri);
response.Redirect(redirectUri, endResponse: true);
return;
}
var principal = token.GetPrincipal();
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
}
public static string GetLoginUrl(HttpApplication application)
{
var request = application.Context.Request;
var requestUrl = new Uri(request.Url, request.RawUrl);
var loginAddress = String.Format("https://{0}/authorize", Auth0Domain);
var client_id = Auth0ClientId;
var scope = "openid profile";
var response_type = "code";
var redirect_uri = GetRedirectUrl(application);
var state = requestUrl.AbsolutePath; // no query
StringBuilder strb = new StringBuilder();
strb.Append(loginAddress);
strb.AppendFormat("?client_id={0}", WebUtility.UrlEncode(client_id));
strb.AppendFormat("&scope={0}", WebUtility.UrlEncode(scope));
strb.AppendFormat("&response_type={0}", WebUtility.UrlEncode(response_type));
strb.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(redirect_uri));
strb.AppendFormat("&state={0}", WebUtility.UrlEncode(state));
return strb.ToString();
}
// spec: https://docs.auth0.com/logout
public static string GetLogoutUrl(HttpApplication application)
{
var request = application.Context.Request;
var logoutAddress = String.Format("https://{0}/logout", Auth0Domain);
var returnTo = request.Url.GetLeftPart(UriPartial.Authority) + LogoutCompletePath;
StringBuilder strb = new StringBuilder();
strb.Append(logoutAddress);
strb.AppendFormat("?returnTo={0}", WebUtility.UrlEncode(returnTo));
return strb.ToString();
}
public static byte[] EncodeCookie(Auth0Token token)
{
var bytes = token.ToBytes();
for (int i = 0; i < DefaultCookieTransforms.Length; ++i)
{
bytes = DefaultCookieTransforms[i].Encode(bytes);
}
return bytes;
}
public static Auth0Token DecodeCookie(byte[] bytes)
{
try
{
for (int i = DefaultCookieTransforms.Length - 1; i >= 0; --i)
{
bytes = DefaultCookieTransforms[i].Decode(bytes);
}
return Auth0Token.FromBytes(bytes);
}
catch (Exception ex)
{
Auth0Trace.WriteLine("DecodeCookie failed with {0}", ex);
// bad cookie
return null;
}
}
public static Auth0Token AuthenticateUser(HttpApplication application, out string redirectUri)
{
redirectUri = null;
var request = application.Context.Request;
var requestUrl = new Uri(request.Url, request.RawUrl);
if (!requestUrl.AbsolutePath.Equals(LoginCallbackPath, StringComparison.OrdinalIgnoreCase))
{
return ReadSessionCookie(application);
}
var query = HttpUtility.ParseQueryString(requestUrl.Query);
var code = query["code"];
if (String.IsNullOrEmpty(code))
{
return ReadSessionCookie(application);
}
var tokenRequestUri = String.Format("https://{0}/oauth/token", Auth0Domain);
var client_id = Auth0ClientId;
var client_secret = Auth0ClientSecret;
var redirect_uri = GetRedirectUrl(application);
var payload = new StringBuilder("grant_type=authorization_code");
payload.AppendFormat("&client_id={0}", WebUtility.UrlEncode(client_id));
payload.AppendFormat("&client_secret={0}", WebUtility.UrlEncode(client_secret));
payload.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(redirect_uri));
payload.AppendFormat("&code={0}", WebUtility.UrlEncode(code));
var webRequest = (HttpWebRequest)WebRequest.Create(tokenRequestUri);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
using (var stream = webRequest.GetRequestStream())
{
var bytes = Encoding.UTF8.GetBytes(payload.ToString());
stream.Write(bytes, 0, bytes.Length);
}
try
{
var webResponse = (HttpWebResponse)webRequest.GetResponse();
using (var stream = webResponse.GetResponseStream())
{
var token = Auth0Token.FromStream(stream);
WriteSessionCookie(application, token);
redirectUri = query["state"];
return token;
}
}
catch (WebException ex)
{
Auth0Trace.WriteLine("POST {0} failed with {1}", tokenRequestUri, ex);
throw HandleOAuthError(ex, tokenRequestUri);
}
}
public static Auth0Token ReadSessionCookie(HttpApplication application)
{
var request = application.Context.Request;
// read user cookie
var cookies = request.Cookies;
var strb = new StringBuilder();
int index = 0;
while (true)
{
var cookieName = LiveAuth;
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 token = DecodeCookie(bytes);
if (token == null || !token.IsValid())
{
RemoveSessionCookie(application);
return null;
}
return token;
}
public static void WriteSessionCookie(HttpApplication application, Auth0Token token)
{
var request = application.Context.Request;
var response = application.Context.Response;
var bytes = EncodeCookie(token);
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(LiveAuth);
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=/");
if (request.Url.Scheme == "https")
{
setCookie.Append("; secure");
}
setCookie.Append("; HttpOnly");
response.Headers.Add("Set-Cookie", setCookie.ToString());
}
var cookies = request.Cookies;
var index = chunkCount;
while (true)
{
var cookieName = LiveAuth;
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[] { LiveAuth })
{
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;
}
}
}
static Exception HandleOAuthError(WebException ex, string requestUri)
{
var response = ex.Response;
if (response != null)
{
using (var stream = response.GetResponseStream())
{
var error = Auth0OAuthError.FromStream(stream);
if (error != null && !String.IsNullOrEmpty(error.error_description))
{
return new InvalidOperationException(String.Format("Failed with {0} POST {1}", error.error_description, requestUri), ex);
}
}
}
return new InvalidOperationException(String.Format("Failed with {0} POST {1}", ex.Message, requestUri), ex);
}
static string GetRedirectUrl(HttpApplication application)
{
var request = application.Context.Request;
return request.Url.GetLeftPart(UriPartial.Authority) + LoginCallbackPath;
}
public class Auth0OAuthError
{
public string error { get; set; }
public string error_description { get; set; }
public static Auth0OAuthError FromStream(Stream stream)
{
var serializer = new JavaScriptSerializer();
using (var reader = new StreamReader(stream))
{
var token = serializer.Deserialize<Auth0OAuthError>(reader.ReadToEnd());
return token;
}
}
}
}
}