From d0f8fcdcf7ac524f4e49d370bc4a7f70fa1df787 Mon Sep 17 00:00:00 2001 From: Daniel Stolt Date: Tue, 10 Nov 2015 09:19:38 +0100 Subject: [PATCH] Changed FormsAuthenticationService to remember that authenticated user is non-item throughout the request. Fixes #5997 --- .../Providers/FormsAuthenticationService.cs | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Orchard/Security/Providers/FormsAuthenticationService.cs b/src/Orchard/Security/Providers/FormsAuthenticationService.cs index 346e4059a..136b068b0 100644 --- a/src/Orchard/Security/Providers/FormsAuthenticationService.cs +++ b/src/Orchard/Security/Providers/FormsAuthenticationService.cs @@ -22,9 +22,16 @@ namespace Orchard.Security.Providers { private IUser _signedInUser; private bool _isAuthenticated; + // This fixes a performance issue when the forms authentication cookie is set to a + // user name not mapped to an actual Orchard user content item. If the request is + // authenticated but a null user is returned, multiple calls to GetAuthenticatedUser + // will cause multiple DB invocations, slowing down the request. We therefore + // remember if the current user is a non-Orchard user between invocations. + private bool _isNonOrchardUser; + public FormsAuthenticationService( - ShellSettings settings, - IClock clock, + ShellSettings settings, + IClock clock, IMembershipService membershipService, IHttpContextAccessor httpContextAccessor, ISslSettingsProvider sslSettingsProvider, @@ -37,7 +44,7 @@ namespace Orchard.Security.Providers { _membershipValidationService = membershipValidationService; Logger = NullLogger.Instance; - + ExpirationTimeSpan = TimeSpan.FromDays(30); } @@ -82,7 +89,7 @@ namespace Orchard.Security.Providers { if (createPersistentCookie) { cookie.Expires = ticket.Expiration; } - + httpContext.Response.Cookies.Add(cookie); _isAuthenticated = true; @@ -113,6 +120,10 @@ namespace Orchard.Security.Providers { } public IUser GetAuthenticatedUser() { + + if (_isNonOrchardUser) + return null; + if (_signedInUser != null || _isAuthenticated) return _signedInUser; @@ -126,7 +137,7 @@ namespace Orchard.Security.Providers { // The cookie user data is {userName.Base64};{tenant}. var userDataSegments = userData.Split(';'); - + if (userDataSegments.Length < 2) { return null; } @@ -147,6 +158,7 @@ namespace Orchard.Security.Providers { _signedInUser = _membershipService.GetUser(userDataName); if (_signedInUser == null || !_membershipValidationService.CanAuthenticateWithCookie(_signedInUser)) { + _isNonOrchardUser = true; return null; }