Back to List

OAuth 2.0 β€” The Principle of Third-Party Authentication

Learn what OAuth 2.0 is, why it doesn't directly receive passwords, and how the Authorization Code Flow works.

Intermediate
|
14min
|
Verified (2026-07)
OAuthSocial LoginAuthentication FlowAuthorization CodeAccess Token
Progress0/55 (0%)

OAuth 2.0: The Principles of Third-Party Authentication

After completing this topic

You will understand the problem that OAuth 2.0 solves, the complete flow of the Authorization Code Flow, and the roles of the Access Token and Refresh Token.


Why don't we ask for passwords?

When you click on a "Login with Google" or "Login with Kakao" button, you don't enter your password into our service. Instead, you are redirected to a Google screen, where you log in to Google and then return.

Why is it so complicated? It's simple: we shouldn't give passwords to other servers.

If a service asks you to "Enter your Google account email and password," that service can store your password. If it is leaked, your entire Google account could be compromised. OAuth solves this problem by giving a "permission token" instead of a password.


The Four Players

OAuth has four roles:

RoleMeaningExample
Resource OwnerThe user (owner of the data)You
ClientThe service we createdOur web app
Authorization ServerThe server responsible for authenticationGoogle Authentication Server
Resource ServerThe server where user data residesGoogle Profile API

The names aren't intuitive. Note that the "Client" is not the user, but our server. From the OAuth perspective, our service is requesting "Give me some data" from Google, so it is the Client.


Authorization Code Flow

This is the most commonly used flow. Let's look at it step by step:

text
1. User clicks "Login with Google."
2. Our server redirects to the Google authorization server.
   β†’ Includes client_id, redirect_uri, and scope in the URL.
3. The user logs in to Google and clicks "Allow this app."
4. Google sends an "authorization code" to the redirect_uri.
5. Our server requests a token from Google using the authorization code and client_secret.
6. Google issues an Access Token.
7. Our server requests user information using the Access Token.

The key is that there are two exchanges. First, we receive an authorization code (one-time use), and then we use it to get the real token. Why don't we just get the token in one step?

In step 4, the authorization code is sent as a URL parameter. URLs are stored in the browser history and logged. If the token were included here, someone could see it. The authorization code is one-time use and expires quickly, so even if it is leaked, the damage is limited.

In step 5, the actual token exchange happens through server-to-server communication (back-channel). It includes the client_secret, which is never exposed to the browser.


Access Token and Refresh Token

javascript
// Example of the token structure that Google responds with
{
  "access_token": "ya29.a0AfH6SM...",
  "expires_in": 3600,          // 1 hour
  "refresh_token": "1//0eXyz...",
  "token_type": "Bearer",
  "scope": "email profile"
}
TokenLifetimeUse
Access TokenShort (usually 1 hour)Used for API calls
Refresh TokenLong (weeks to months)Used to reissue Access Tokens

When the Access Token expires, we get a new Access Token using the Refresh Token. We don't have to ask the user to "log in again" every time.

Why don't we make the Access Token longer? To minimize the damage period in case the token is leaked. If a 1-hour token is leaked, the risk is only for 1 hour, but if a 1-year token is leaked, the risk is for 1 year.


Scope: The Range of Permissions

text
https://accounts.google.com/o/oauth2/v2/auth?
  client_id=OUR_CLIENT_ID&
  redirect_uri=http://localhost:3000/callback&
  scope=email+profile&
  response_type=code

scope defines how much access is granted. If it's email profile, you can only get the email and profile picture, and you can't see Google Drive files.

When the user clicks "Allow this app," the screen shows "This app will access your email address," which is the scope.

Principle of least privilege: request only what you need. If you request "all permissions," the user will be scared and refuse.


When Implementing in Our Service

Here's what you need to know when implementing:

  1. Provider Registration: Register the app in the Google/Kakao developer console and get the client_id and client_secret.
  2. redirect_uri Setting: Register the callback URL where you will receive the authorization code. Redirection will be rejected if it is not registered.
  3. State Value Verification: Include a random string for CSRF prevention in the request and verify the match in the callback.
javascript
// Callback handling in Express (concept)
app.get('/callback', async (req, res) => {
  const { code, state } = req.query;

  // 1. State verification (CSRF prevention)
  if (state !== req.session.oauthState) {
    return res.status(403).send('Invalid state');
  }

  // 2. Exchange authorization code for token (server β†’ Google, back-channel)
  const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
    method: 'POST',
    body: new URLSearchParams({
      code,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      redirect_uri: REDIRECT_URI,
      grant_type: 'authorization_code',
    }),
  });

  const { access_token } = await tokenRes.json();

  // 3. Request user information using the Access Token
  const userRes = await fetch(
    'https://www.googleapis.com/oauth2/v2/userinfo',
    { headers: { Authorization: `Bearer ${access_token}` } }
  );
  const user = await userRes.json();

  // 4. Store user in session
  req.session.user = user;
  res.redirect('/');
});

Key Takeaways

OAuth 2.0 is a protocol that delegates permissions using tokens instead of passwords. Authorization Code Flow is a two-step exchange: authorization code (one-time use) β†’ Access Token (short-term) β†’ API call. Access Tokens are short-lived, and Refresh Tokens are used to renew them – this design minimizes damage in case of a leak.

β†’ In the next topic, we will actually implement Passport.js + Google OAuth.

πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...