I am trying to use cookie authentication in an Asp.net core app (dnx 4.5). Note that because I have a custom authentication mechanism (radius), I am not using the out-of-the-box mechanism provided by core Authentication. When the user is not authenticated I want to redirect to a login page.
I have added in Startup.cs the following code. The idea is to be redirected to the Login Controller when the user has not been authenticated:
app.UseCookieAuthentication(options => { options.LoginPath = new Microsoft.AspNet.Http.PathString("/Login"); });
In my Home controller I have:
[Authorize]
public IActionResult Index()
{
return View();
}
In my Login controller I return a view corresponding to the radius login form:
[AllowAnonymous]
public IActionResult Index()
{
return View();
}
However, when I run the app, the redirect never happens. Looking at the console output I see the following:
warn: Microsoft.AspNet.Mvc.Controllers.ControllerActionInvoker[0]
Authorization failed for the request at filter 'Microsoft.AspNet.Mvc.Filters.AuthorizeFilter'.
info: Microsoft.AspNet.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNet.Mvc.Infrastructure.MvcRouteHandler[2]
Executed action ThingsProjectorWeb.Controllers.HomeController.Index in 0ms
info: Microsoft.AspNet.Hosting.Internal.HostingEngine[2]
Request finished in 0.0016ms 401
Any help on how to configure this correctly would be greatly appreciated. Thanks!
OK figured it out. It is all explained here: https://docs.asp.net/en/latest/security/authentication/cookie.html
I was missing the options.AutomaticChallenge = true;
, which automatically redirects you to the Login Controller.
Here is the updated options:
app.UseCookieAuthentication(options => {
options.LoginPath = new Microsoft.AspNet.Http.PathString("/Login");
options.AutomaticChallenge = true;
});
UPDATE:
As of version 1.1.0
it's:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Login"),
AutomaticChallenge = true
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With