You've surely seen a "Log in with Google" button on a sign-up page. One click, and you're in without making a new password. That's social login: logging in with an account you already have at another service, such as Google. Behind it, the app has to be sure who just arrived.
Picture an inter-school event. The organisers don't make you a new name badge. They look at the student card your school issued. They check that it is genuine, that the issuing school is right, that it is meant for this event, and that it has not expired. Then they match its student number against the list of participants. In social login, the organisers are School Portal, and the list of participants is the accounts on the Portal. The student card is called the id_token, its issuer is Google, and its student number is the sub claim (the Google account's id).
OAuth + OpenID Connect
In the previous lesson, OAuth 2.0 Flow, School Portal got permission to use Mr. Andi's calendar. That is authorization. To log someone in, the Portal needs something else: who just logged in. The access token does not answer that question, because an access token is only a key for calling an API.
OpenID Connect (OIDC) is a layer on top of OAuth 2.0 that adds identity. The flow is exactly the same (authorization code, state, PKCE). Seen from the Portal's code, there are only two differences:
- The scope starts with
openid:openid email profile. - The answer from
/token(the endpoint where the code is exchanged for a token) carries one more token, theid_token: a JWT signed by Google, with claims about the user who logged in.
So two things work behind the "Log in with Google" button: OAuth 2.0 for authorization, plus OpenID Connect for identity. This is the payload of Siti's id_token, exactly as in the Lab (login on 9 October 2026 at 07:00 school time, UTC+7):
{
"iss": "https://accounts.google.com",
"aud": "1234567890-portal.apps.googleusercontent.com",
"sub": "110169484474386276334",
"email": "[email protected]",
"email_verified": true,
"hd": "school.test",
"name": "Siti",
"iat": 1791504000,
"exp": 1791507600
}
Checking the id_token, in order
Reading the payload is not trusting it. The server checks it in this order and stops at the first check that fails. The order is the same as the organisers' checks at the inter-school event: a genuine card, the right issuing school, a card for this event, not expired, then the student number.
| Order | Claim | Must be | If it fails |
|---|---|---|---|
| 1 | signature | matches Google's public key (https://www.googleapis.com/oauth2/v3/certs) |
forged or altered token |
| 2 | iss |
https://accounts.google.com (or accounts.google.com) |
not from Google |
| 3 | aud |
School Portal's client_id |
the token was made for another app |
| 4 | exp |
greater than the current time, in Unix seconds | expired |
| 5 | sub |
present | no account ID |
The signature is checked by a library (ready-made code written by others) with Google's public key. The algorithm is RS256, not HS256 as in the example of the JSON Web Token (JWT) lesson: Google signs with a private key that only Google holds, and the Portal only needs the public key. This code reads the payload, then checks its claims:
const GOOGLE_CLIENT_ID = "1234567890-portal.apps.googleusercontent.com";
function decodePayload(idToken) {
const part = idToken.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
return JSON.parse(atob(part)); // reading only, not verifying
}
function checkClaims(claims, nowSeconds) {
if (claims.iss !== "https://accounts.google.com" && claims.iss !== "accounts.google.com") return "iss";
if (claims.aud !== GOOGLE_CLIENT_ID) return "aud";
if (claims.exp <= nowSeconds) return "exp";
if (!claims.sub) return "sub";
return null; // passes
}
checkClaimsreturns the name of the first check that fails, ornullwhen all of them pass.audis the one most often forgotten. For example, Siti's token for MyCanteen, the school canteen app. That token also really comes from Google, but itsaudis MyCanteen's client_id. The Portal must refuse it.expis in seconds, andnowSecondsmust be in seconds too, not milliseconds. 07:05 is1791504300, so a token whoseexpis1791500400(06:00) is refused.atobis right only for ASCII text: anameclaim ofJoséis read asJosé. For such text, turn it into bytes first and useTextDecoder, as in the JSON Web Token (JWT) lesson.
Linking to an account
Once the token passes, the Portal looks for the user in this order:
function findOrLink(db, claims) {
const social = db.socialAccounts.find((s) => s.provider === "google" && s.providerId === claims.sub);
if (social) return db.users.find((u) => u.id === social.userId); // seen before: look up by sub
if (claims.email_verified !== true) return { error: "email not verified" };
let user = db.users.find((u) => u.email === claims.email);
const domain = claims.email.split("@")[1]; // Google is the authority for gmail.com and Workspace domains (hd)
if (user && domain !== "gmail.com" && claims.hd !== domain) return { error: "prove the old account" };
if (!user) {
user = { id: db.nextId++, name: claims.name, email: claims.email, role: "student" };
db.users.push(user);
}
db.socialAccounts.push({ userId: user.id, provider: "google", providerId: claims.sub });
return user;
}
- By
subin thesocial_accountstable (columnsuser_id,provider,provider_id). Thesubnever changes for one Google account, while an email can be changed. - By email, only when
email_verifiedistrue. An unverified email is not proven to belong to the person logging in, so it may not be used to link to anyone's account. Verified is still not enough. Google is the authority (it can confirm who owns the email) only for@gmail.comemail and Google Workspace email, Google's service for schools and offices. Workspace email is marked by thehdclaim, the organisation's domain. Any other email may have changed owner since Google checked it. So link automatically only when the email's domain isgmail.comor equalshd. Otherwise, ask for proof of the old account first: its password, or a code sent to that email. - Nothing at all yet: create a new account from Google's data (name, email), with the lowest role, then link it to its
sub.
The results in the Lab:
| id_token | Looked up by | Result |
|---|---|---|
| Siti, first time | no sub yet, the verified email matches user 1 |
a new row in social_accounts, logged in as Siti |
| Siti, second time | sub found |
logged in as Siti, the email is not looked at |
| Nadia, a new student | neither sub nor email found |
user 5 is created (role student) and linked |
[email protected], email_verified: false |
no sub yet, the email is not verified |
not linked to Mr. Andi's account |
Siti already has an account with [email protected], and her Google account uses the same email. When she presses "Log in with Google" for the first time, she doesn't get a new account. She is linked to her existing one, because the email is the same, verified, and its hd is school.test (the school uses Google Workspace). Nadia gets id 5, not 4, because id 4 used to be Rizky's, and an auto-increment id (a number the database adds automatically, one higher each time) is never reused.
In Laravel: Socialite
Laravel Socialite runs the OAuth and OIDC flow. For Google, its default scopes are already openid, profile, email.
// routes/api.php
Route::get('/auth/google/redirect', fn () => Socialite::driver('google')->stateless()->redirect());
Route::get('/auth/google/callback', function () {
$google = Socialite::driver('google')->stateless()->user();
$user = SocialAccount::firstWhere(['provider' => 'google', 'provider_id' => $google->getId()])?->user;
if (! $user) {
abort_unless(($google->getRaw()['email_verified'] ?? false) === true, 403, 'Google email not verified.');
$domain = Str::after($google->getEmail(), '@');
$googleOwnsEmail = $domain === 'gmail.com' || ($google->getRaw()['hd'] ?? null) === $domain;
abort_if(! $googleOwnsEmail && User::where('email', $google->getEmail())->exists(), 409, 'Sign in with your password first, then link Google.');
$user = User::firstOrCreate(['email' => $google->getEmail()], ['name' => $google->getName(), 'role' => 'student']);
$user->socialAccounts()->create(['provider' => 'google', 'provider_id' => $google->getId()]);
}
return AuthResponse::for($user); // the Portal's own access token + refresh token cookie
});
Socialite::driver('google')picks the Google provider, as configured inconfig/services.php(client_id, client_secret, redirect).->user()exchanges the code for a token, then fetches the profile from Google's userinfo endpoint.getId()is thesub, andgetRaw()holds every claim,email_verifiedandhdincluded. If the email is already used by an account on the Portal, but Google is not the authority for it, the Portal answers409(a conflict with the existing account), with the message: sign in with your password first, then link Google.->stateless()makes Socialite neither store nor compare thestatein the session. It is used when the callback arrives at an API with no session, like BelajarWeb.dev's own API. The app must then protect that flow in another way. If your route has a session (thewebgroup), don't usestateless(). Let Socialite check thestate, and->enablePKCE()works too, since the verifier is kept in the session.- When an app in the browser or on a phone already has the
id_tokenand sends it straight to the API,->userFromToken($idToken)checks its signature with Google's keys,iss,audandexp. AuthResponse::for($user)is a helper (a small function) written for this app. It makes an access token and a refresh token of the Portal's own, as in the Token Refresh Flow lesson. Google's token is not used for the Portal's API.
⚠️ Accounts linked to the wrong person, and tokens that leak
- Linking by email without checking
email_verifiedandhd. Someone else's account could get linked to a Google account that never proved it owns that email. - Searching for the user by email at every login. As soon as Siti changes her email, she gets a new, empty account. Look up by
subfirst. - Only decoding the
id_token, never checking it.atobreads, it does not verify. Check the signature,iss,audandexp, or let the library do it. - Putting the app's token in the redirect URL (
/dashboard?token=...). URLs end up in the history and in logs. Send it in anHttpOnlycookie or a JSON body.
TL;DR: Log in with Google = OAuth 2.0 (authorization, meaning permission) + OpenID Connect (identity). The scope is openid email profile, and the /token endpoint (where the code is exchanged for a token) answers with an id_token: a JWT signed by Google that says who logged in. Check in order: the signature (Google's public key), iss (the issuer), aud (must be your app's client_id), exp (in seconds), then sub (the Google account's id, which never changes). After that, look the account up by sub in the social_accounts table. Link by email only when email_verified is true and Google is the authority for that email (it can confirm who owns it): gmail.com, or hd (the Google Workspace domain) equal to the email's domain. When there is no account yet, create a new one. In Laravel: Socialite::driver('google')->stateless()->user(), then issue your app's own tokens.
⚡ OAuth for permission, OpenID Connect for identity
Meaning: Two things work behind the Google login button: OAuth 2.0 for authorization (permission), plus OpenID Connect for identity (who logged in). The flow is exactly the same as in OAuth, only the scope starts with openid (openid email profile). Then the answer from the /token endpoint, where the code is exchanged for a token, carries one more token: the id_token, a JWT signed by Google that says who logged in.
⚡ Check the id_token, in order
Write:
function checkClaims(claims, nowSeconds) {
if (claims.iss !== "https://accounts.google.com" && claims.iss !== "accounts.google.com") return "iss";
if (claims.aud !== GOOGLE_CLIENT_ID) return "aud";
if (claims.exp <= nowSeconds) return "exp";
if (!claims.sub) return "sub";
return null; // passes
}
Meaning: Reading the payload is not trusting it. claims is the payload of the id_token. Once the library has checked the signature, this code checks iss (the issuer must be Google), aud (must be GOOGLE_CLIENT_ID, School Portal's client_id), exp (the expiry time, in seconds like nowSeconds), then sub (the Google account's id). The function returns the name of the first check that fails, or null when all of them pass. aud is the check most often forgotten. For example, Siti, a School Portal student, has a token for another app. It really comes from Google too, but its aud is not the Portal's client_id.
⚡ Look up by sub first
Guess first: Siti's Google account is already linked to her account on the Portal, then she changes her Google email. When she logs in again, does she get a new account?
No. The Portal looks up by sub first, and the sub never changes for one Google account. Looking up by email would give Siti a new, empty account instead.
Meaning: The order: look for the sub in the social_accounts table, the table that links Google accounts to Portal users. Then look up by email, but only when email_verified is true (Google has confirmed that email) and Google is the authority for it (it can confirm who owns it): gmail.com, or a school or office domain marked by hd. Nothing at all yet: create a new account with the lowest role, then link it to its sub.