我正在测试[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)的任何控制器上包含[Authorize]属性.
这个GitHub仓库中有一个非常基本的示例可能会提供一些指导:https: //github.com/leastprivilege/AspNet5TemplateCookieAuthentication