重定向至“在ASP.NET 5中使用Cookie身份验证进行具有Authorize属性的登录”诊断树

本文关键字:Authorize 属性 诊断 登录 身份验证 ASP NET Cookie 重定向 | 更新日期: 2023-09-27 18:27:49

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

这是我在控制器中登录的代码(非常简单)。

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

有什么想法吗?

谢谢!!

重定向至“在ASP.NET 5中使用Cookie身份验证进行具有Authorize属性的登录”诊断树

您的Startup.cs应该如下所示:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    LoginPath = "/account/login",
    AuthenticationScheme = "Cookies",
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

设置AutomaticChallenge将使[Authorize]属性起作用。请确保在您希望重定向(302)发生的任何控制器上都包含[授权]属性。

这个GitHub回购中有一个非常基本的示例,可能会提供一些指导:https://github.com/leastprivilege/AspNet5TemplateCookieAuthentication

Startup.cs:中尝试此操作

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

这在控制器

IAuthenticationManager authManager = Request.GetOwinContext().Authentication;
authManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);