我正在尝试使用Cookie设置身份验证,但SignInAsync
似乎无效。
我的签名方法至少目前是这样的:
[HttpPost]
public async Task<IActionResult> Login(string username, string password)
{
if (username != "foo" || password != "bar")
{
return View();
}
//Sign in
var claims = new List<Claim>
{
new Claim("name", "admin")
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(principal);
//Redirect
return RedirectToAction("home");
}
Home
是具有Authorize
属性的操作。
如果我提供了正确的用户名和密码,我可以跳过SignInAsync
电话,看似没有异常。但是,在重定向时,我最终返回登录页面,因为我还没有登录。
Startup.cs
列在下面:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/admin/login/";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=home}/{action=index}/{id?}");
});
app.UseAuthentication();
}
}
我缺少什么或如何调试/获取有关出错的更多信息?
答案 0 :(得分:1)
根据Tratcher的评论,请在app.UseAuthentication();
之前使用app.UseMvc();
。