我正在尝试使用identity和ef配置cookie身份验证。到目前为止,我能够在Controller响应中拥有一个有效的Set-Cookie。浏览器发回此cookie,但AuthorizeFilter总是重定向到Login页面,因此Authentication似乎不起作用。我要求配置什么? 到目前为止,这是我在Startup中的ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors(o => o.AddPolicy("Cors", builder =>
{
builder.WithOrigins(Configuration["AllowedOrigins"].Split(","))
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
}));
services.AddDbContext<MyIdentityDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<MyIdentityDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options => {
if (!String.IsNullOrEmpty(Configuration["AuthCookieDomain"]))
{
options.Cookie.Domain = Configuration["AuthCookieDomain"];
}
options.Cookie.Name = Configuration["AuthCookieName"];
options.Cookie.HttpOnly = false;
options.Cookie.SameSite = SameSiteMode.None;
});
}
然后,我在启动时配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("Cors");
app.UseMvc();
app.UseAuthentication();
}
然后,我的Action实际上成功设置了cookie
// GET api/values
[HttpPost]
public async Task<ActionResult> Post([FromBody] AuthPost post)
{
if (post == null || String.IsNullOrEmpty(post.UserName) || String.IsNullOrEmpty(post.Password))
{
return BadRequest();
}
var result = await signInManager.PasswordSignInAsync(post.UserName, post.Password, true, false);
if (result.Succeeded)
{
return Ok();
}
return Unauthorized();
}
最后,我的其他具有授权的操作属性不起作用(始终重定向到登录)
[HttpGet]
[Authorize]
public async Task<ActionResult> Get()
{
var user = await userManager.GetUserAsync(User);
return Ok(new { UserName = user.UserName });
}
答案 0 :(得分:3)
好的,ConfigureApplicationCookie是一种工作方式。导致此问题的原因是app.UseMvc();
和app.UseAuthentication();
app.UseAuthentication()
!之前调用 app.UseMvc()