Jesper Plantener
Jesper Plantener

Reputation: 229

Authorize redirect 401 not working

I have an implementation in .net-core using cookieauthentication.

However, i am experiencing the following issue: When accessing a page when I am not logget in and where the AuthorizationAttribute is set, it just shows me a blank page, instead of redirecting me to the login page.

Fiddler tells me that I am receiving a 401 unauthorized response. The Location Header is set to /Home, but is ignored by the browser, since the status code is 401.

The cookie implementation looks like this:

          app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            LoginPath = new PathString("/Home"),
            LogoutPath = new PathString("/logout"),
            AccessDeniedPath = new PathString("/accessdenied")
        });

AuthorizationAttribute works fine, since I can access the page as soon as I am logged in.

From my understanding, the AutomaticChallenge = true should take care of this. Is this wrong?

Upvotes: 0

Views: 644

Answers (1)

Ross
Ross

Reputation: 2141

You are experiencing issue with AutomaticChallenge option. This option is causing a conflict between IISIntegration and Cookie middleware, see detailed notes here.

If you are using [Authorize], the solution would be to add the following code to your startup.cs inside ConfigureServices(IServiceCollection services)

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder("Cookies").RequireAuthenticatedUser().Build();
});

I tested it and it works!

Upvotes: 1

Related Questions