c# - 使用 ASP.NET 5 中的 cookie 身份验证重定向到使用属性授权的登录

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

我正在测试 [Authorize] 属性,但如果用户尚未登录,我无法重定向到登录页面(Chrome 检查器返回 401)。

这是我的代码,用于在我的Controller 中进行登录(非常简单)。

if (model.UserName == "admin" && model.Password == "test")
{
    var claims = new[] { new Claim("name", model.UserName), new Claim(ClaimTypes.Role, "Admin") };
    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
    return RedirectToAction("Index", "Home");
}

这是我在 Startup.cs 中用于登录的配置:

app.UseCookieAuthentication(options =>
    {
        options.AutomaticAuthenticate = true;
        options.LoginPath = new PathString("/Account/Login");
    });

有什么想法吗?

谢谢!!

最佳答案

您的 Startup.cs 应如下所示:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    LoginPath = "/account/login",

    AuthenticationScheme = "Cookies",
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

设置 AutomaticChallenge 将使 [Authorize] 属性起作用。请务必在您希望重定向 (302) 发生的任何 Controller 上包含 [Authorize] 属性。

此 GitHub 存储库中有一个非常基本的示例,可以提供一些指导: https://github.com/leastprivilege/AspNet5TemplateCookieAuthentication

关于c# - 使用 ASP.NET 5 中的 cookie 身份验证重定向到使用属性授权的登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437344/

相关文章:

asp.net-core - Controller.json 设置 Serialization.ReferenceLoopHandling

multithreading - 在.Net Core的后台插入批量数据

c# - 为什么它需要默认构造函数而不是直接使用我的工厂方法?

c# - Google Apis C# FileDatastore

c# - TcpListener : how to stop listening while awaiting AcceptTcpClientAsync()?

c# - 使用 ASP.net 将 Highcharts 连接到数据库

c# - ASP.NET Core 中失败的授权要求的错误状态代码

c# - 你能捕捉到使用Powershell调用C#控制台应用抛出的错误码和异常信息吗?

asp.net-core - 如何在 Asp.Net Core 中使用 OData

c# - 如何使用 Angular 取消 .Net Core Web API 请求?