- 添加Identity服务:在Startup.cs的ConfigureServices方法中添加Identity服务
services.AddDefaultIdentity()
.AddEntityFrameworkStores();
- 添加第三方登录服务:在Startup.cs的ConfigureServices方法中添加第三方登录服务
services.AddAuthentication()
.AddGoogle(options =>
{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
})
.AddFacebook(options =>
{
options.AppId = Configuration["Authentication:Facebook:AppId"];
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
- 创建账户控制器AccountController:在Controllers文件夹下创建AccountController,包含方法Login、ExternalLoginCallback、ExternalLogin
public class AccountController : Controller
{
private readonly SignInManager _signInManager;
private readonly UserManager _userManager;
public AccountController(SignInManager signInManager, UserManager userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
return View(model);
}
[HttpGet]
[AllowAnonymous]
public async Task ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View("Login", new LoginViewModel());
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ModelState.AddModelError(string.Empty, "Error loading external login information.");
return View("Login", new LoginViewModel());
}