Table of contents
No headings in the article.
When it comes to "Login with Google", this is where OAuth 2.0 and OpenID Connect (OIDC) intersect. I was wondering how OAuth deals with this since it's mainly about giving authorization, not authentication. But OIDC is the one taking care of authentication.
OIDC is built on top of OAuth 2.0, specifically for authentication. When you implement "Login with Google", you're using both:
OAuth 2.0 handles authorization ("Can this app access your Google calendar?")
OIDC handles authentication ("Who are you?")
Here's what happens in a "Login with Google" flow:
interface OIDCTokenResponse {
access_token: string;
id_token: string; // This is the key difference!
refresh_token?: string;
}
async function handleGoogleLogin(authCode: string) {
// Exchange auth code for tokens
const tokens = await oauth.getTokens(authCode);
// The id_token is a JWT containing user info
const decodedIdToken = jwt.decode(tokens.id_token);
// Now we know who the user is
const user = {
email: decodedIdToken.email,
name: decodedIdToken.name,
// Google's unique identifier for this user
sub: decodedIdToken.sub,
};
// Create or update user in your system
await upsertUser(user);
// Create a session for your app
const sessionToken = await createSessionToken(user);
return sessionToken;
}
It's also worth mentioning that people typically create their own access and refresh tokens despite being authenticated by e.g. Google. This way, they've more control over the tokens and how a user is authenticated on their own system.