Joel
Joel

Reputation: 111

ASP.NET 5 (VNEXT) Cookie Authentication Problems after Migrating from Beta 8 to RC1

I have been creating an application in ASP.NET 5 (VNext) for months now and have been steadily upgrading application as newer versions of ASP.NET 5 have been released. After applying RC1 to my Beta 8 app, my Cookie Authentication stopped working. When a page needs authentication/authorization, the web browser just shows a blank screen.

In Startup.cs, I have the following code in my ConfigureServices method:

services.AddAuthentication();

In Startup.cs, I have the following code in my Configure method:

app.UseCookieAuthentication(options =>
{
    options.AccessDeniedPath = new PathString("/Account/AccessDenied");
    options.LoginPath = new PathString("/Account/Login");
    options.SessionStore = (new MemoryCacheSessionStore());
    options.CookieName = "D1_AWARE";
    options.LogoutPath = new PathString("/Account/LogOut");
    options.ExpireTimeSpan = new TimeSpan(1, 0, 0);
});

In my HomeController, I have the "Authorize" attribute tagged to my Index() method as follows:

[Authorize]
public IActionResult Index()
{
    return View();
}

If I remove the Authorize attribute, everything works fine (but security is bypassed). If I leave it, the browser goes blank.

As I stated earlier, everything was working fine prior to RC1. If anyone can help me out, it would be greatly appreciated.

Upvotes: 1

Views: 561

Answers (1)

steve
steve

Reputation: 1555

Looks like they changed some options between Beta 8 and RC 1. Try changing it to what I use below:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
     // ...

     app.UseCookieAuthentication(options =>
        {
            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;

            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            options.SlidingExpiration = true;

            options.LoginPath = new PathString("/Account/Login");
            options.LogoutPath = new PathString("/Account/Logout");
            options.AccessDeniedPath = new PathString("/Account/AccessDenied");

            options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.CookieSecure = CookieSecureOption.SameAsRequest;
            options.CookieHttpOnly = true;
        });

    // ...
}

You have a few different settings (like no sliding expiration) but this should provide a good working start.

The magic seems to be in these lines:

options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;

They force ASP.net 5 to handle the redirection to the login page and to get the Authorize attribute to work.

Other upgraders may find this link useful: http://wildermuth.com/2015/11/18/Upgrading_ASP_NET_5_Beta_8_to_RC1

The main point is that app.UpseCookieAuthentication has moved to Configure in Startup.cs

Upvotes: 2

Related Questions