Belajar
← All lessons

How OAuth login works

Log in with another site

Browser
print.test
photos.test
Photos API

print.test/server.js

// print.test, the app you log in toapp.get("/login", (req, res) => {  const state = randomString();  req.session.state = state;  res.redirect("https://photos.test/authorize?" +    new URLSearchParams({ response_type: "code",      client_id: CLIENT_ID, redirect_uri: CALLBACK,      scope: "profile photos.read", state }));}); app.get("/callback", async (req, res) => {  if (req.query.state !== req.session.state) throw 400;  const r = await fetch("https://photos.test/token", {    method: "POST",    body: new URLSearchParams({      grant_type: "authorization_code",      code: req.query.code, redirect_uri: CALLBACK,      client_id: CLIENT_ID, client_secret: SECRET,    }),  });  const { access_token } = await r.json();  const me = await fetch("https://api.photos.test/me", {    headers: { Authorization: `Bearer ${access_token}` },  });});

photos.test/server.js

// photos.test, the auth serverapp.get("/authorize", (req, res) => {  const client = clients.get(req.query.client_id);  if (!req.session.user) return res.render("sign-in");  res.render("consent", { client, scope: req.query.scope });}); app.post("/authorize", (req, res) => {  const code = codes.issue(req.session.user, req.body);  res.redirect(`${redirect_uri}?code=${code}&state=${state}`);}); app.post("/token", (req, res) => {  clients.check(req.body.client_id, req.body.client_secret);  const grant = codes.use(req.body.code);  res.json({ access_token: tokens.issue(grant) });});

Scopes decide what the token can do and nothing more

Scopes print.test asks for
Consent screen
What the token can call

api.photos.test/server.js

// api.photos.testconst need = (scope) => (req, res, next) => {  const token = tokens.find(bearer(req));  if (!token.scope.split(" ").includes(scope)) {    return res.status(403).json({ error: "insufficient_scope" });  }  next();}; app.get("/me", need("profile"), me);app.get("/me/email", need("email"), email);app.get("/photos", need("photos.read"), list);app.post("/photos", need("photos.write"), upload);

PKCE protects the code when an app can't keep a secret

Phone app
photos.test
Other app

app.js

// the phone app, before it opens the browserconst verifier = base64url(randomBytes(32));const hash = await crypto.subtle.digest("SHA-256", encode(verifier));const challenge = base64url(hash);openBrowser(authorizeUrl + "&code_challenge=" + challenge +  "&code_challenge_method=S256"); // after the redirect: no secret, just the verifierawait post("https://photos.test/token", { code, code_verifier: verifier });

photos.test/server.js

// photos.test, at /authorizeconst code = codes.issue(user, { code_challenge });res.redirect("printapp://callback?code=" + code); // at /tokenconst grant = codes.get(req.body.code);const hash = base64url(sha256(req.body.code_verifier));if (hash !== grant.code_challenge) {  return res.status(400).json({ error: "invalid_grant" });}res.json({ access_token: tokens.issue(grant) });

The state check stops a forged callback

The callback comes fromYour loginAttacker's linkNo state
print.test receives

code is for
saved state
URL state

Skip the check, and an attacker's link logs you in to their account

print.test/server.js

app.get("/callback", async (req, res) => {  const { code, state } = req.query;  if (!state || state !== req.session.state) {    return res.status(400).send("state mismatch");  }  delete req.session.state;  const { access_token } = await exchange(code);  req.session.user = await whoAmI(access_token);});

Topics

Next: How passkeys work

Open lesson