I am stuck at Google authentication in .NET Core Web API project. I am using Google as my external authenticator, everything is working fine except when the call comes back to my handler, an exception occurs. Details are here:
I am using .NET 8 minimal APIs, Identity and EF core. This is how I am adding authentication and authorization:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = configuration["Auth:Google:ClientId"] ?? string.Empty;
googleOptions.ClientSecret = configuration["Auth:Google:ClientSecret"] ?? string.Empty;
googleOptions.Scope.Add("email"); // to get primary email address
googleOptions.Scope.Add("profile"); // to get personal public info like name, image etc.
});
services.AddAuthorization();
This is how I am adding Identity
services.AddIdentityCore<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<OctuFitContext>()
.AddSignInManager<SignInManager<ApplicationUser>>();
This is how I am challenging authentication
var redirectUrl = "api/auth/google/handler";
var properties = signInManager.ConfigureExternalAuthenticationProperties("Google", redirectUrl);
return await Task.FromResult(Results.Challenge(properties));
The problem is when the call comes back to my handler, I try to get the external login info like this
var info = await signInManager.GetExternalLoginInfoAsync();
And I get the following exception
No authentication handler is registered for the scheme 'Identity.External'. The registered schemes are: Cookies, Google. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Identity.External",...)?
The same exact code is working in my other project with the controllers. I know it has nothing to do with controllers but am I missing something? I am really confused here and spent a lot of my time fixing this but all in vain :(
Try adding the below to your .AddGoogle() handler
googleOptions.SignInScheme = IdentityConstants.ExternalScheme;
in addition to the other options that you have set