-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
FormsAuthenticationModule.cs
490 lines (410 loc) · 21.9 KB
/
FormsAuthenticationModule.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//------------------------------------------------------------------------------
// <copyright file="FormsAuthenticationModule.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* FormsAuthenticationModule class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Security {
using System.Globalization;
using System.Web;
using System.Text;
using System.Web.Configuration;
using System.Web.Caching;
using System.Web.Handlers;
using System.Collections;
using System.Web.Util;
using System.Security.Principal;
using System.Security.Permissions;
using System.Web.Management;
public sealed class FormsAuthenticationModule : IHttpModule {
// Config values
private static bool _fAuthChecked;
private static bool _fAuthRequired;
internal static bool FormsAuthRequired {
get {
return _fAuthRequired;
}
}
private bool _fOnEnterCalled;
private FormsAuthenticationEventHandler _eventHandler;
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Web.Security.FormsAuthenticationModule'/>
/// class.
/// </para>
/// </devdoc>
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public FormsAuthenticationModule() {
}
/// <devdoc>
/// This is a Global.asax event which must be
/// named FormsAuthenticate_OnAuthenticate event. It's used by advanced users to
/// customize cookie authentication.
/// </devdoc>
public event FormsAuthenticationEventHandler Authenticate {
add {
_eventHandler += value;
}
remove {
_eventHandler -= value;
}
}
public void Dispose() {
}
public void Init(HttpApplication app) {
// authentication is an app level setting only
// so we can read app config early on in an attempt to try and
// skip wiring up event delegates
if (!_fAuthChecked) {
_fAuthRequired = (AuthenticationConfig.Mode == AuthenticationMode.Forms);
_fAuthChecked = true;
}
if (_fAuthRequired) {
// initialize if mode is forms auth
FormsAuthentication.Initialize();
app.AuthenticateRequest += new EventHandler(this.OnEnter);
app.EndRequest += new EventHandler(this.OnLeave);
}
}
////////////////////////////////////////////////////////////
// OnAuthenticate: Forms Authentication modules can override
// this method to create a Forms IPrincipal object from
// a WindowsIdentity
private void OnAuthenticate(FormsAuthenticationEventArgs e) {
HttpCookie cookie = null;
////////////////////////////////////////////////////////////
// Step 1: If there are event handlers, invoke the handlers
if (_eventHandler != null)
_eventHandler(this, e);
////////////////////////////////////////////////////////////
// Step 2: Check if the event handler created a user-object
if (e.Context.User != null) {
// do nothing because someone else authenticated
return;
}
if (e.User != null) {
// the event handler created a user
e.Context.SetPrincipalNoDemand(e.User);
return;
}
////////////////////////////////////////////////////////////
// Step 3: Extract the cookie and create a ticket from it
bool cookielessTicket = false;
FormsAuthenticationTicket ticket = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket);
////////////////////////////////////////////////////////////
// Step 4: See if the ticket was created: No => exit immediately
if (ticket == null || ticket.Expired)
return;
////////////////////////////////////////////////////////////
// Step 5: Renew the ticket
FormsAuthenticationTicket ticket2 = ticket;
if (FormsAuthentication.SlidingExpiration)
ticket2 = FormsAuthentication.RenewTicketIfOld(ticket);
////////////////////////////////////////////////////////////
// Step 6: Create a user object for the ticket
e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket2), new String[0]));
////////////////////////////////////////////////////////////
// Step 7: Browser does not send us the correct cookie-path
// Update the cookie to show the correct path
if (!cookielessTicket && !ticket2.CookiePath.Equals("/"))
{
cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null) {
cookie.Path = ticket2.CookiePath;
}
}
////////////////////////////////////////////////////////////
// Step 8: If the ticket was renewed, save the ticket in the cookie
if (ticket2 != ticket)
{
if(cookielessTicket && ticket2.CookiePath != "/" && ticket2.CookiePath.Length > 1) {
FormsAuthenticationTicket tempTicket = FormsAuthenticationTicket.FromUtc(ticket2.Version, ticket2.Name, ticket2.IssueDateUtc,
ticket2.ExpirationUtc, ticket2.IsPersistent, ticket2.UserData,
"/");
ticket2 = tempTicket;
}
String strEnc = FormsAuthentication.Encrypt(ticket2, !cookielessTicket);
if (cookielessTicket) {
e.Context.CookielessHelper.SetCookieValue('F', strEnc);
e.Context.Response.Redirect(e.Context.Request.RawUrl);
} else {
if (cookie != null)
cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) {
cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEnc);
cookie.Path = ticket2.CookiePath;
}
if (ticket2.IsPersistent)
cookie.Expires = ticket2.Expiration;
cookie.Value = strEnc;
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.HttpOnly = true;
if (FormsAuthentication.CookieDomain != null)
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.SameSite = FormsAuthentication.CookieSameSite;
e.Context.Response.Cookies.Remove(cookie.Name);
e.Context.Response.Cookies.Add(cookie);
}
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
private void OnEnter(Object source, EventArgs eventArgs) {
_fOnEnterCalled = true;
HttpApplication app;
HttpContext context;
app = (HttpApplication)source;
context = app.Context;
#if DBG
Trace("*******************Request path: " + context.Request.RawUrl);
#endif
////////////////////////////////////////////////////////
// Step 2: Call OnAuthenticate virtual method to create
// an IPrincipal for this request
OnAuthenticate( new FormsAuthenticationEventArgs(context) );
////////////////////////////////////////////////////////
// Skip AuthZ if accessing the login page
// We do this here to force the cookieless helper to fish out and
// remove the token from the URL if it's present there.
CookielessHelperClass cookielessHelper = context.CookielessHelper;
if (AuthenticationConfig.AccessingLoginPage(context, FormsAuthentication.LoginUrl)) {
context.SetSkipAuthorizationNoDemand(true, false /*managedOnly*/);
cookielessHelper.RedirectWithDetectionIfRequired(null, FormsAuthentication.CookieMode);
}
if (!context.SkipAuthorization) {
context.SetSkipAuthorizationNoDemand(AssemblyResourceLoader.IsValidWebResourceRequest(context), false /*managedOnly*/);
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
private void OnLeave(Object source, EventArgs eventArgs) {
if (_fOnEnterCalled)
_fOnEnterCalled = false;
else
return; // no need to continue if we skipped OnEnter
HttpApplication app;
HttpContext context;
app = (HttpApplication)source;
context = app.Context;
////////////////////////////////////////////////////////////
// Step 1: Check if we are using cookie authentication and
// if authentication failed
if (context.Response.StatusCode != 401)
return;
////////////////////////////////////////////////////////////
// Change 401 to a redirect to login page
// Don't do it if the redirect is suppressed for this response
if (context.Response.SuppressFormsAuthenticationRedirect) {
return;
}
// Don't do it if already there is ReturnUrl, already being redirected,
// to avoid infinite redirection loop
String strUrl = context.Request.RawUrl;
if (strUrl.IndexOf("?" + FormsAuthentication.ReturnUrlVar + "=", StringComparison.Ordinal) != -1
|| strUrl.IndexOf("&" + FormsAuthentication.ReturnUrlVar + "=", StringComparison.Ordinal) != -1) {
return;
}
////////////////////////////////////////////////////////////
// Step 2: Get the complete url to the login-page
String loginUrl = null;
if (!String.IsNullOrEmpty(FormsAuthentication.LoginUrl))
loginUrl = AuthenticationConfig.GetCompleteLoginUrl(context, FormsAuthentication.LoginUrl);
////////////////////////////////////////////////////////////
// Step 3: Check if we have a valid url to the login-page
if (loginUrl == null || loginUrl.Length <= 0)
throw new HttpException(SR.GetString(SR.Auth_Invalid_Login_Url));
////////////////////////////////////////////////////////////
// Step 4: Construct the redirect-to url
String strRedirect;
int iIndex;
CookielessHelperClass cookielessHelper;
// if(context.Request.Browser["isMobileDevice"] == "true") {
// //__redir=1 is marker for devices that post on redirect
// if(strUrl.IndexOf("__redir=1") >= 0) {
// strUrl = SanitizeUrlForCookieless(strUrl);
// }
// else {
// if(strUrl.IndexOf('?') >= 0)
// strSep = "&";
// else
// strSep = "?";
// strUrl = SanitizeUrlForCookieless(strUrl + strSep + "__redir=1");
// }
// }
// Create the CookielessHelper class to rewrite the path, if needed.
cookielessHelper = context.CookielessHelper;
if (loginUrl.IndexOf('?') >= 0) {
loginUrl = FormsAuthentication.RemoveQueryStringVariableFromUrl(loginUrl, FormsAuthentication.ReturnUrlVar);
strRedirect = loginUrl + "&" + FormsAuthentication.ReturnUrlVar + "=" + HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding);
}
else {
strRedirect = loginUrl + "?" + FormsAuthentication.ReturnUrlVar + "=" + HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding);
}
////////////////////////////////////////////////////////////
// Step 5: Add the query-string from the current url
iIndex = strUrl.IndexOf('?');
if (iIndex >= 0 && iIndex < strUrl.Length - 1) {
strRedirect += "&" + strUrl.Substring(iIndex + 1);
}
cookielessHelper.SetCookieValue('F', null); // remove old ticket if present
cookielessHelper.RedirectWithDetectionIfRequired(strRedirect, FormsAuthentication.CookieMode);
////////////////////////////////////////////////////////////
// Step 6: Do the redirect
context.Response.Redirect(strRedirect, false);
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Private method for decrypting a cookie
private static FormsAuthenticationTicket ExtractTicketFromCookie(HttpContext context, String name, out bool cookielessTicket) {
FormsAuthenticationTicket ticket = null;
string encValue = null;
bool ticketExpired = false;
bool badTicket = false;
try {
try {
////////////////////////////////////////////////////////////
// Step 0: Check if we should use cookieless
cookielessTicket = CookielessHelperClass.UseCookieless(context, false, FormsAuthentication.CookieMode);
////////////////////////////////////////////////////////////
// Step 1: Check URI/cookie for ticket
if (cookielessTicket) {
encValue = context.CookielessHelper.GetCookieValue('F');
} else {
HttpCookie cookie = context.Request.Cookies[name];
if (cookie != null) {
encValue = cookie.Value;
}
}
////////////////////////////////////////////////////////////
// Step 2: Decrypt encrypted ticket
if (encValue != null && encValue.Length > 1) {
try {
ticket = FormsAuthentication.Decrypt(encValue);
} catch {
if (cookielessTicket)
context.CookielessHelper.SetCookieValue('F', null);
else
context.Request.Cookies.Remove(name);
badTicket = true;
//throw;
}
if (ticket == null) {
badTicket = true;
}
if (ticket != null && !ticket.Expired) {
if (cookielessTicket || !FormsAuthentication.RequireSSL || context.Request.IsSecureConnection) // Make sure it is NOT a secure cookie over an in-secure connection
return ticket; // Found valid ticket
}
if (ticket != null && ticket.Expired) {
ticketExpired = true;
}
// Step 2b: Remove expired/bad ticket
ticket = null;
if (cookielessTicket)
context.CookielessHelper.SetCookieValue('F', null);
else
context.Request.Cookies.Remove(name);
}
////////////////////////////////////////////////////////////
// Step 3: Look in QueryString
if (FormsAuthentication.EnableCrossAppRedirects) {
encValue = context.Request.QueryString[name];
if (encValue != null && encValue.Length > 1) {
if (!cookielessTicket && FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect)
cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode); // find out for sure
try {
ticket = FormsAuthentication.Decrypt(encValue);
} catch {
badTicket = true;
//throw;
}
if (ticket == null) {
badTicket = true;
}
}
// Step 3b: Look elsewhere in the request (i.e. posted body)
if (ticket == null || ticket.Expired) {
encValue = context.Request.Form[name];
if (encValue != null && encValue.Length > 1) {
if (!cookielessTicket && FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect)
cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode); // find out for sure
try {
ticket = FormsAuthentication.Decrypt(encValue);
} catch {
badTicket = true;
//throw;
}
if (ticket == null) {
badTicket = true;
}
}
}
}
if (ticket == null || ticket.Expired) {
if (ticket != null && ticket.Expired)
ticketExpired = true;
return null; // not found! Exit with null
}
if (FormsAuthentication.RequireSSL && !context.Request.IsSecureConnection) // Bad scenario: valid ticket over non-SSL
throw new HttpException(SR.GetString(SR.Connection_not_secure_creating_secure_cookie));
////////////////////////////////////////////////////////////
// Step 4: Create the cookie/URI value
if (cookielessTicket) {
if (ticket.CookiePath != "/") {
FormsAuthenticationTicket tempTicket = FormsAuthenticationTicket.FromUtc(ticket.Version, ticket.Name, ticket.IssueDateUtc,
ticket.ExpirationUtc, ticket.IsPersistent, ticket.UserData,
"/");
ticket = tempTicket;
encValue = FormsAuthentication.Encrypt(ticket);
}
context.CookielessHelper.SetCookieValue('F', encValue);
string strUrl = FormsAuthentication.RemoveQueryStringVariableFromUrl(context.Request.RawUrl, name);
context.Response.Redirect(strUrl);
} else {
HttpCookie cookie = new HttpCookie(name, encValue);
cookie.HttpOnly = true;
cookie.Path = ticket.CookiePath;
if (ticket.IsPersistent)
cookie.Expires = ticket.Expiration;
cookie.Secure = FormsAuthentication.RequireSSL;
if (FormsAuthentication.CookieDomain != null)
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.SameSite = FormsAuthentication.CookieSameSite;
context.Response.Cookies.Remove(cookie.Name);
context.Response.Cookies.Add(cookie);
}
return ticket;
} finally {
if (badTicket) {
WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.AuditFormsAuthenticationFailure,
WebEventCodes.InvalidTicketFailure);
} else if (ticketExpired) {
WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.AuditFormsAuthenticationFailure,
WebEventCodes.ExpiredTicketFailure);
}
}
} catch {
throw;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static void Trace(String str) {
Debug.Trace("cookieauth", str);
}
}
}