我正在测试 [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/