ASP.Net Identity with episerver not working when deployed

1k Views Asked by At

I'm currently working on a site using EpiServer CMS 8 and replacing the login with Owin/ASP.Net Identity.

Everything is working fine on local IIS but when deploying to our test server navigating to /episerver/ doesn't redirect to the login page but directly gives a 401.2 unauthorized result.

Below is my startup class

[assembly: OwinStartup(typeof(Website.Startup))]
namespace Website
{
    public class Startup
    {
        private const string PathRoot = "~/";
        private const string LogoutUrl = "/Account/Logout";
        private const string LoginUrl = "/Account/Login";
        private const string BackendLoginUrl = "~/BackendAccount/";
        private const string BackendLogoutUrl = "~/Util/Logout.aspx";

        public void ConfigureAuth(IAppBuilder app)
        {
            Configuration(app);
        }
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString(VirtualPathUtility.ToAbsolute(LoginUrl)),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
                    OnApplyRedirect = ApplyRedirect
                }
            }, PipelineStage.Authenticate);

          app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.Map(VirtualPathUtility.ToAbsolute(LogoutUrl), map =>
            {
                map.Run(ctx =>
                {
                    ctx.Authentication.SignOut();
                    return Task.Run(() => ctx.Response.Redirect(VirtualPathUtility.ToAbsolute(PathRoot)));
                });
            });

            app.Map(VirtualPathUtility.ToAbsolute(BackendLogoutUrl), map =>
            {
                map.Run(ctx =>
                {
                    ctx.Authentication.SignOut();
                    return Task.Run(() => ctx.Response.Redirect(VirtualPathUtility.ToAbsolute(PathRoot)));
                });
            });
            app.UseStageMarker(PipelineStage.MapHandler);
        }
        private static void ApplyRedirect(CookieApplyRedirectContext context)
        {
            string backendPath = Paths.ProtectedRootPath.TrimEnd('/');

            if (context.Request.Uri.AbsolutePath.StartsWith(backendPath, StringComparison.CurrentCultureIgnoreCase) && !context.Request.User.Identity.IsAuthenticated)
            {
                context.RedirectUri = VirtualPathUtility.ToAbsolute(BackendLoginUrl) +
                        new QueryString(
                            context.Options.ReturnUrlParameter,
                            context.Request.Uri.AbsoluteUri);
            }

            context.Response.Redirect(context.RedirectUri);
        }
    }
}

My web.config includes these sections

<authentication mode="None">
</authentication>
<membership defaultProvider="OwinMembershipProvider" userIsOnlineTimeWindow="10" hashAlgorithmType="HMACSHA512">
  <providers>
    <clear /
    <add name="OwinMembershipProvider"
         type="Website.Shared.Providers.OwinMembershipProvider"
         enablePasswordRetrival="false"
         enablePasswordReset="true"
         requiresQuestionAndAnswer="false"
         requiresUniqueEmail="false"
         passwordFormat="Hashed"
         passwordStrengthRegularExpression=""
         minRequiredPasswordLength="6"
         minRequiredNonalphanumericCharacters="0"
         connectionString="TestConnection"
         />
      </providers>
</membership>
<roleManager enabled="true" defaultProvider="OwinRoleProvider" cacheRolesInCookie="true">
  <providers>
    <clear />
    <add name="OwinRoleProvider" type="Website.Shared.Providers.OwinRoleProvider"/>
  </providers>
</roleManager>

I've tried to compare iis settings between the servers and I can find no difference. I really have no clue how to troubleshoot this and I've tried everything listed on the Owin guide for startup handling. The OwinMembershipProvder and OwinRoleProvider are based on the code from http://www.mogul.com/om-mogul/blogg/owin-membership-and-role-provider-for-episerver but extended and modified to fit our requirements

1

There are 1 best solutions below

0
On BEST ANSWER

Solved this by first clearing ASP.Net temporary files and then restarting the site with web.config set as

<add key="owin:AutomaticAppStartup" value="true" />
<add key="owin:AppStartup" value="Website.Startup" />

I had previously tested what I though was every possible combination of these two values without success.

I can't say for sure but the combination of clearing the cache and removing the assembly name from the AppStartup key may have been the solution.