我使用Postman向/api/account/login发送请求并用户登录,然后将请求发送到/api/account/logout,它成功注销,但是当我在前端执行此操作时,我填写登录表单并发送请求,我得到response.ok,但是当我尝试将请求发送到/api/account/logout时,它会抛出401 Unauthorized。
我认为我的启动.cs配置服务方法存在问题,但我不确定它是什么
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(x =>
x.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("RemoteConnection")));
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<AppDbContext, int>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.Cookies.ApplicationCookie.AutomaticChallenge = false;
});
// services.AddScoped<UserGroupRepository, UserGroupRepository>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<ISurveysRepository, SurveysRepository>();
services.AddScoped<IUsersRepository, UsersRepository>();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
ReactHotModuleReplacement = true
});
}
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
我注意到,在使用表单发送请求时,即使在这里用户也未获得授权
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _signInManager.PasswordSignInAsync(request.UserName, request.Password, true, false);
if (!result.Succeeded)
{
return StatusCode((int)HttpStatusCode.Conflict, new ErrorResponse
{
ErrorMessage = "Invalid User Name or Password."
});
}
if (User.Identity.IsAuthenticated)
return NoContent();
else
return BadRequest(ModelState);
}
是我的 API 中的错误.js执行请求方法,我错过了
credentials: 'include'