Search code examples
asp.net-coreweb-configsession-variableswindows-authentication

.NET Core 3.1 & Windows Authentication Kills Session Variables


Whenever I enable Windows Authentication on my .NET Core 3.1 application, my session variables no longer seem to persist across requests. Whenever I turn off Windows Authentication, the Session variables work again.

I enabled Session variables in the ConfigureServices() section of Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
//......
    services.AddSession(delegate (SessionOptions options)
    {
        options.IdleTimeout = TimeSpan.FromSeconds(1800);
        options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
        options.Cookie.SameSite = SameSiteMode.Strict;
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });
//......
} 

I enabled Windows Authentication using web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <remove name="aspNetCore" />
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" hostingModel="InProcess" disableStartUpErrorPage="false">
        <environmentVariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
        </environmentVariables>
      </aspNetCore>
      <security>
        <authentication>
          <windowsAuthentication enabled="true" />
          <anonymousAuthentication enabled="false" />
        </authentication>
      </security>      
    </system.webServer>
  </location>
</configuration>

I set session variables like this in one Razor page (SET.cshtml):

<div>
    @Context.Session.SetString("testvar", "123");
</div>

And on another Razor page (GET.cshtml), I check to see if the variable persisted:

<div>
    @Context.Session.GetString("testvar")
</div>

When Windows Authentication is enabled in web.config, the session variable "testvar" does not persist when going from SET.cshtml to GET.cshtml (GET.cshtml should display "123" but it does not). When I disable Windows Authentication, it starts working again (GET.cshtml properly displays "123").

What could be the problem?


Solution

  • I figured out the issue. I wasn't calling "app.UseAuthorization()" in Startup.cs.

    app.UseAuthorization() needs to be called in the Configure() method in Startup.cs in order for session variables to persist across requests when Windows authentication is enabled in .NET Core:

    enter image description here