本文介绍了Asp.net核心授权重定向未发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我在Startup.cs中添加了以下代码.当用户未通过身份验证时,该想法将被重定向到登录控制器:

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!

推荐答案

确定.此处说明了所有内容: https://docs.asp.net/en/latest/security/authentication/cookie.html

OK figured it out. It is all explained here: https://docs.asp.net/en/latest/security/authentication/cookie.html

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

I was missing the options.AutomaticChallenge = true;, which automatically redirects you to the Login Controller.

以下是更新的选项:

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

这篇关于Asp.net核心授权重定向未发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:06