在 ASP.NET Core 应用程序中,使用外部身份提供程序进行身份验证是很常见的。 很多人都会遇到无法成功使用外部身份提供程序登录的问题。 这通常是由于代码方面的问题所导致的。 下面是一些可以解决这些问题的解决方法和示例代码。
services.AddAuthentication()
.AddGoogle(options =>
{
IConfigurationSection googleAuthNSection = Configuration.GetSection("Authentication:Google");
options.ClientId = googleAuthNSection["ClientId"];
options.ClientSecret = googleAuthNSection["ClientSecret"];
});
[HttpGet]
[AllowAnonymous]
public async Task ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return RedirectToAction("Login", "Account", new { ReturnUrl = returnUrl });
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ModelState.AddModelError(string.Empty, "Error loading external login information.");
return RedirectToAction("Login", "Account", new { ReturnUrl = returnUrl });
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
return LocalRedirect(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToAction("Lockout");
}
else
{
// 如果用户不存在,则创建一个帐户
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
var user = new IdentityUser { UserName = email, Email = email };
var