代码示例: 后端验证登录信息和生成AntiForgeryToken:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(LoginWith2fa), new { returnUrl = returnUrl, model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToAction(nameof(Lockout));
}
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
[ValidateAntiForgeryToken]
public IActionResult Logout()
{
_signInManager.SignOutAsync().Wait();
_logger.LogInformation("User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task ExternalLogin([FromBody] ExternalLoginViewModel model)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
return Ok();
}
if (result.IsLockedOut)
{
ModelState.AddModelError(string.Empty, "User account is locked out.");
return StatusCode(StatusCodes.Status423Locked);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return BadRequest();
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ExternalLoginConfirmation([FromBody] RegisterViewModel model)
{
return Ok();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Register([FromBody] RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
return Ok();
}
AddErrors(result);
}
return BadRequest(ModelState);
}
[AllowAnonymous]
public IActionResult AccessDenied()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// 这里对登录信息进行了验证,并调用SignInAsync方法进行登录