【发布时间】:2020-01-13 07:42:53
【问题描述】:
我使用 Angular 7 创建了 Web 应用程序 front-end, DotNetCore 2.2 为 back-end API(用于 db 的 SQL Server)。 最初创建项目时,我没有添加Authentication,因为 不需要 UI 页面。我计划将身份验证与 cookie 一起使用。
虽然 Login 和 [Authorize] 运行良好,但 Logout 不适用于 signInManager.SignOutAsync()。
微软声明: “SignOutAsync 清除存储在 cookie 中的用户声明。 调用 SignOutAsync 后不要重定向,否则用户将不会退出。” 似乎 cookie 没有被删除,并且被 API 接受为有效(除非它过期)。 我尝试使用 Response.Cookies.Delete() 和 HttpContext.SignOutAsync() 没有成功。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CORS", builder =>
{
builder.WithOrigins("http://localhost:42000")
.AllowAnyHeader()
.AllowCredentials();
});
});
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<NGDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<NGUser, IdentityRole>()
.AddEntityFrameworkStores<NGDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
// some options...
});
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
options.SlidingExpiration = true;
//options.CookieName = "MyCookie";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddScoped<NamesService, NamesService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
InitialSeeder.Seed(app);
}
else
{
app.UseHsts();
}
app.UseCors("CORS");
app.UseHttpsRedirection();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private UserManager<NGUser> userManager;
private SignInManager<NGUser> signInManager;
public AuthController(UserManager<NGUser> userManager, SignInManager<NGUser> signInManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
}
[HttpPost("Login")]
public async Task<ActionResult> Login(LoginModel model)
{
var user = await this.userManager.FindByNameAsync(model.Username);
if (user == null)
{
return Unauthorized();
}
var signInResult = await this.signInManager.PasswordSignInAsync(user, model.Password, false, false);
if (!signInResult.Succeeded)
{
return Unauthorized();
}
return Ok();
}
[HttpPost("Logout")]
public async Task<ActionResult> Logout()
{
await this.signInManager.SignOutAsync();
return Ok();
}
}
是否可以从身份登录注销方法中受益? 还是应该使用自定义方法?
【问题讨论】:
-
我发现了这个类似的问题,这有帮助吗? stackoverflow.com/questions/41122053/…
-
我猜API根本不需要重定向。因此,如果 signInManager.SignOutAsync() 重定向它不是 API 的正确方法?
-
你怎么知道用户已经登录,你使用令牌吗?也许你可以使用 IdentityServer4:docs.microsoft.com/en-us/aspnet/core/security/authentication/…
标签: asp.net-core asp.net-identity