c# - 用户身份验证后自动重定向不起作用

标签 c# asp.net-core asp.net-core-mvc

我和我的团队正在 ASP .NET 5 中启动一个新的网站项目,我正在尝试建立我们的用户身份验证和授权策略的基础。

我目前正在为返回的用户使用基于 cookie 的身份验证,因此我将以下内容添加到我的 Startup.cs 的 Configure 方法中:

        // Redirect to login page if user is not logged in.
        app.UseCookieAuthentication(options =>
        {
            options.AutomaticAuthentication = true;
            options.ExpireTimeSpan = new System.TimeSpan(0, 1, 0);
            options.SlidingExpiration = true;
            options.LoginPath = "/Login";
            options.ReturnUrlParameter = "ReturnUrl";
        });

身份验证服务也被添加到 ConfigureServices 方法中。

我担心的是 LoginPath 参数:虽然当我的中间件/过滤器(我都尝试过)返回 401 代码时,自动重定向到登录页面可以正常工作,但从登录页面自动重定向回最初请求的页面不会' 工作:即使登录成功,浏览器仍停留在登录页面上。

我强烈怀疑问题出在我的 Controller 中。这是它的(稍微简化的)源代码:

[Route("[controller]")]
[AllowAnonymous]
public class LoginController : Controller
{
    private static readonly string AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async System.Threading.Tasks.Task<ActionResult> Post(LoginInfo infos)
    {
        if (ValidateLogin(infos))
        {
            await Context.Authentication.SignInAsync(AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            }, 
            AuthenticationScheme)));
        }

        return View("Index");
    }

    private static bool ValidateLogin(LoginInfo infos)
    {
        return infos.Username == "abc" && infos.Password == "def";
    }
}

(为清楚起见,删除了一些代码,例如,如果用户名/密码组合被拒绝,则显示一条错误消息)

View 非常简单,包含一个简单的表单,提供几个编辑框并将用户/密码发布到 Controller (同样,为清楚起见删除了错误消息):

@using (Html.BeginForm("Post", "Login", FormMethod.Post))
{
    <div>
        <h2>Login Page</h2>
        <p>
            @Html.Label("Username")
            @Html.Editor("Username")
        </p>

        <p>
            @Html.Label("Password")
            @Html.Password("Password")
        </p>

        <p>
            <input type="submit" value="Attempt login" />
        </p>
    </div>
}

我已经能够通过在单独的 Controller 中获取用户身份和声明来检查用户登录是否正常工作。初始重定向到登录页面也能正常工作(即,当我尝试在未登录的情况下访问网站的 protected 部分时,我被重定向到“/Login”),并且重定向的 URL 正确包含 ReturnUrl 查询参数。我还尝试在处理 Post 操作时访问 Referer URL,并设法通过从 Controller 手动返回 RedirectResult 来强制触发重定向,因此 ReturnUrl 本身的内容也一定是好的。

所以...谁能帮我理解为什么重定向到返回 URL 不会自动执行?

编辑:根据 CookieAuthenticationOptions.LoginPath 的文档:

Summary: The LoginPath property informs the middleware that it should change an outgoing 401 Unauthorized status code into a 302 redirection onto the given login path. The current url which generated the 401 is added to the LoginPath as a query string parameter named by the ReturnUrlParameter. Once a request to the LoginPath grants a new SignIn identity, the ReturnUrlParameter value is used to redirect the browser back to the url which caused the original unauthorized status code. If the LoginPath is null or empty, the middleware will not look for 401 Unauthorized status codes, and it will not redirect automatically when a login occurs.

粗体部分是我试图利用的部分...重定向到静态页面(即手动将 Redirect() 返回到某个硬编码页面)不是我要在这里完成的。

最佳答案

问题是您总是在成功登录后返回到索引 View :

[HttpPost]
public async System.Threading.Tasks.Task<ActionResult> Post(LoginInfo infos)
{
        if (ValidateLogin(infos))
        {
            await Context.Authentication.SignInAsync(AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            }, 
            AuthenticationScheme)));
        }

        return View("Index"); //the problem is here
}

尝试将 return View("Index"); 替换为您希望将用户重定向到的 View (可能在另一个 Controller 上)。你可以试试 RedirectToAction : Redirect to Action in another controller .像这样的东西:

return RedirectToAction("Index", "Home");

在您的情况下,如果您依赖框架为您进行重定向,请尝试:

[HttpPost]
public async System.Threading.Tasks.Task Post(LoginInfo infos)
{
        if (ValidateLogin(infos))
        {
            await Context.Authentication.SignInAsync(AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            }, 
            AuthenticationScheme)));
        }
 }

关于c# - 用户身份验证后自动重定向不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31967238/

相关文章:

c# - ASP.NET MVC : Register action filter without modifying controller

c# - 服务器端 SignalR 连接在长时间正常运行后失败

asp.net-core - ASP.Net Core 本地化

asp.net - ASP 5 MVC 6 HTTP 错误 404.15 部署到 IIS 时

C#暂停程序执行

c# - 如何确定目录路径是否被 SUBST'd

authentication - ASP Net Core - 将外部身份提供者与个人用户帐户混合以进行审计跟踪

asp.net - ASP.Net MVC 6 中的全局错误日志记录

c# - 拼写出来的数字 (int) 的打印值

c# - 使用 Json.NET/NEST/Elasticsearch 在 ASP.NET Core 应用程序中找不到方法错误