【问题标题】:Asp.net Core Authorize Redirection Not HappeningAsp.net Core 授权重定向未发生
【发布时间】:2016-05-01 13:50:55
【问题描述】:

我正在尝试在 Asp.net 核心应用程序 (dnx 4.5) 中使用 cookie 身份验证。请注意,因为我有一个自定义身份验证机制(半径),所以我没有使用 core Authentication 提供的开箱即用机制。当用户未通过身份验证时,我想重定向到登录页面。

我在 Startup.cs 中添加了以下代码。这个想法是在用户尚未通过身份验证时重定向到登录控制器:

app.UseCookieAuthentication(options => { options.LoginPath = new Microsoft.AspNet.Http.PathString("/Login"); });

在我的 Home 控制器中,我有:

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

在我的登录控制器中,我返回一个对应于半径登录表单的视图:

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

但是,当我运行应用程序时,重定向永远不会发生。查看控制台输出,我看到以下内容:

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

任何有关如何正确配置的帮助将不胜感激。谢谢!

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    好的,想通了。都在这里解释了:https://docs.asp.net/en/latest/security/authentication/cookie.html

    我错过了options.AutomaticChallenge = true;,它会自动将您重定向到登录控制器。

    这里是更新的选项:

    app.UseCookieAuthentication(options => {
                    options.LoginPath = new Microsoft.AspNet.Http.PathString("/Login");
                    options.AutomaticChallenge = true;
                });
    

    更新:

    截至1.1.0 版本是:

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
             LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Login"),
             AutomaticChallenge = true
    });
    

    【讨论】:

    • 这在 IISIntergration 上对我不起作用。在 Kestrel 上我得到一个完美的 302,但在 IIS 上我得到一个 401。你做了什么让它在 IISIntergration 上也能工作吗?
    • @MitchDart 可能是 IIS 默认使用 FormsAuthentication。尝试将 添加到网络配置中?
    • 这对我也不起作用。坚持尝试重定向两天。在此之前是否需要添加服务?我有:services.AddSession();这应该增加对此的支持。已经厌倦了Core。它只是不起作用。
    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2020-10-30
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多