Introduction
ShopNest customers expect Sign in with Google — OAuth2 lets users authenticate via external providers while Identity stores the local account link.
After this article you will
- Explain OAuth2 authorization code flow simply
- Configure Google, Facebook, Microsoft providers
- Link external logins to existing local accounts
- Handle email-already-registered conflicts
- Retrieve profile data from provider claims
Prerequisites
- Article 32 — JWT with Refresh Tokens
- ShopNest.Web with EF Core and configuration from Module 3
Concept deep-dive
OAuth2 flow (simplified): User clicks Google → redirect to Google → user consents → Google redirects back with code → ShopNest exchanges code for tokens → create/link Identity user → sign in with cookie.
builder.Services.AddAuthentication()
.AddGoogle(options =>
{
options.ClientId = config["Authentication:Google:ClientId"]!;
options.ClientSecret = config["Authentication:Google:ClientSecret"]!;
})
.AddFacebook(options => { ... })
.AddMicrosoftAccount(options => { ... });
// AccountController external login callback
var info = await _signInManager.GetExternalLoginInfoAsync();
var signInResult = await _signInManager.ExternalLoginSignInAsync(
info.LoginProvider, info.ProviderKey, isPersistent: false);
if (!signInResult.Succeeded)
{
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
var user = await _userManager.FindByEmailAsync(email) ?? new ApplicationUser { ... };
await _userManager.CreateAsync(user);
await _userManager.AddLoginAsync(user, info);
await _signInManager.SignInAsync(user, isPersistent: false);
}
Google setup: Google Cloud Console → OAuth client ID → authorized redirect URI: https://localhost:7xxx/signin-google
Hands-on — ShopNest Social Login E-Commerce
- Register Google OAuth app; store ClientId/Secret in User Secrets.
- Add Google button on login page.
- Link external login to existing email/password account (account settings).
- Show provider avatar from claim picture URL.
Common errors & best practices
- Redirect URI mismatch — exact match required in provider console.
- Creating duplicate users on each Google login — always AddLoginAsync.
- Client secret in frontend — secret stays server-side only.
Interview questions
Q: OAuth2 vs OpenID Connect?
A: OAuth2 authorizes API access; OIDC adds identity layer (id_token with user info). Google login uses OIDC.
Q: Link external to local account?
A: UserManager.AddLoginAsync associates provider key with Identity user.
Summary
- OAuth2 external login reduces password friction
- Identity stores external login provider + key
- Handle duplicate email across providers gracefully
- Secrets in User Secrets, redirect URIs exact match
Previous: JWT with Refresh Tokens
Next: Data Protection and Encryption
FAQ
Facebook app review?
Development mode limited to test users until app review for production.
Store provider access token?
Optional in AspNetUserTokens if calling provider APIs later.