Asp.net Core Authorize Redirection Not Happening

 ̄綄美尐妖づ 提交于 2019-12-05 23:46:10

问题


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!


回答1:


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
});


来源:https://stackoverflow.com/questions/36967426/asp-net-core-authorize-redirection-not-happening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!