When I try to sign in with Google authentication, I encounter an issue that I can't receive information by using signInManager.GetExternalLoginInfoAsync(). This is because Google plus is shutting down. Here I give the overall codes and sources for google authentication. I used ASP.NET core 2.2.
The process of create a Google API console project is :
- Create Google oauth credentials client Id and secret.
- Set up API and configure
1. Create Google oauth credentials client Id and secret.
Learn to create client Id and secret by this link: https://docs.microsoft.com/en-US/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-3.1
Notice: enable SSL, e.g., use https://localhost:44306/signin-google for Authorised redirect URIs in oauth client IDs in Credentials.
2. Set up API and configure
In startup.cs, add configure service :
services.AddAuthentication().AddGoogle(option =>
{
option.ClientId = "597035172561-c50s2qu28fj78tl1lmivb6v8tpsr9qta.apps.googleusercontent.com";
option.ClientSecret = "vGIslMG3NOGqcLKdc8uwmu-n";
//option.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v1/certs";
option.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";
option.ClaimActions.Clear();
option.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
option.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
option.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
option.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
option.ClaimActions.MapJsonKey("urn:google:profile", "link");
option.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
});
Notice: just input clientID and ClientSecret will through an exception "HttpRequestException: An error occurred when retrieving Google user information (Forbidden). Please check if the authentication information is correct and the corresponding Google+ API is enabled." This is because Google plus is shutting down. I tried to add an UserInformationEndpoint but found that I can't receive information by using signInManager.GetExternalLoginInfoAsync(). Codes in the controller are:
[HttpPost]
[AllowAnonymous]
public IActionResult ExternalLogin(string provider, string returnUrl)
{
var redirectUrl = Url.Action("ExternalLoginCallback", "account",
new { ReturnUrl = returnUrl });
var properties = signInManager
.ConfigureExternalAuthenticationProperties(provider,redirectUrl);
return new ChallengeResult(provider, properties);
}
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback
(string returnUrl = null,string remoteError = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
var info = await signInManager.GetExternalLoginInfoAsync();
// info should contain user information after successful signed in google.
var signInResult = await signInManager.
ExternalLoginSignInAsync(info.LoginProvider,
info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
}
Official announcement
https://github.com/aspnet/AspNetCore/issues/6486