在 Startup.cs 中确保已启用 cookie 必要的中间件:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.AccessDeniedPath = "/AccessDeniedPath";
options.LoginPath = "/Login";
options.Cookie.HttpOnly = true;
options.Cookie.Name = "MyApplicationCookie";
options.Cookie.SecurePolicy = CookieSecurePolicy.None;// set to None if you're not using SSL
options.Cookie.SameSite = SameSiteMode.None;// Only set to None if you're not using HTTPS
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
});
}
确保 web api 响应将 cookie 设置为 SameSiteMode=None,以确保在授权操作期间不会出现问题
[HttpGet]
public async Task Login(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
var user = await _userManager.FindByEmailAsync(Input.Email);
var roles = await _userManager.GetRolesAsync(user);
var claims = new List
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.Email, user.Email),
};
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = Input.RememberMe,