Authentication ASP.NET Core 2.0中的AuthorizationAttribute
我正在尝试使用identity和ef配置cookie身份验证。到目前为止,我能够在控制器响应中使用有效的Set Cookie。浏览器将此cookie发送回,但AuthorizeFilter始终重定向到登录页面,因此身份验证似乎不起作用。我可以配置什么? 以下是我目前正在启动的ConfigureServices:Authentication ASP.NET Core 2.0中的AuthorizationAttribute,authentication,cookies,authorization,.net-core,Authentication,Cookies,Authorization,.net Core,我正在尝试使用identity和ef配置cookie身份验证。到目前为止,我能够在控制器响应中使用有效的Set Cookie。浏览器将此cookie发送回,但AuthorizeFilter始终重定向到登录页面,因此身份验证似乎不起作用。我可以配置什么? 以下是我目前正在启动的ConfigureServices: public void ConfigureServices(IServiceCollection services) { services.AddMvc();
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;
});
}
然后,我的操作实际上成功地设置了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();
}
//获取api/值
[HttpPost]
公共异步任务发布([FromBody]AuthPost)
{
if(post==null | | String.IsNullOrEmpty(post.UserName)| | String.IsNullOrEmpty(post.Password))
{
返回请求();
}
var result=await-signInManager.PasswordSignInAsync(post.UserName,post.Password,true,false);
if(result.successed)
{
返回Ok();
}
未经授权返回();
}
最后,我的另一个带有Authorize属性的操作不起作用(总是重定向到登录)
[HttpGet]
[授权]
公共异步任务Get()
{
var user=await userManager.GetUserAsync(用户);
返回Ok(新的{UserName=user.UserName});
}
好的,配置应用程序OK是工作的方式。导致问题的原因是app.UseMvc()的顺序错误
和app.UseAuthentication()代码>
必须在调用app.UseMvc()之前调用app.UseMvc()
// 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 });
}