Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET core 2.0 cookie authentication - do not redirect [duplicate]

I am using .NET core 2.0 with cookie authentication.
My configuration looks like this:

services
  .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  .AddCookie(options =>
  {
      options.ExpireTimeSpan = TimeSpan.FromDays(1);
      options.SlidingExpiration = true;
      options.Cookie.Name = "authtoken";
  });

When I access unauthorized controller, I am being redirected to /Account/Login

In .NET Core 1.1 I was able to configure this by setting AutomaticChallenge = false.
How can I configure this in .NET Core 2.0?
I just want my controller to return HTTP 403.

like image 926
stkxchng Avatar asked Sep 15 '17 20:09

stkxchng


Video Answer


1 Answers

Unfortunately the flag is well and truly removed. However you can override the "RedirectToLogin" event like so in your ConfigureServices method of your startup.cs

services.AddAuthentication("CookieAuthenticationScheme")
    .AddCookie(options => {
        options.Events.OnRedirectToLogin = (context) =>
        {
            context.Response.StatusCode = 401;
            return Task.CompletedTask;
        };
    });

Couple more tidbits here if you get stuck on the upgrade : https://dotnetcoretutorials.com/2017/09/16/cookie-authentication-asp-net-core-2-0/

Am I right to assume this is because it's an ajax call you are making (Or a Web API in general?). It seems like MS have gone hard with JWT being for Web API, and for Cookie to be for MVC only. Hence why the forced login page.

like image 124
MindingData Avatar answered Sep 22 '22 00:09

MindingData