Skip to content

Authentication Methods (Session · Token · API Key · OAuth) ​

An authentication method is how the server checks "who sent this request (a person or a program), and what they are allowed to do." Typical examples are Basic authentication, sessions, tokens (JWT), API Keys, and OAuth, and each differs in where it keeps the information and what it exchanges.

At a Glance ​

  • First, you need to tell apart two words that look similar.
    • Authentication: checking "who are you?"
    • Authorization: checking "what are you allowed to do?"
  • Analogy: think about entering a company building.
    • Tapping your employee badge to confirm "this really is employee Hong Gildong" is authentication.
    • Checking whether that badge can also open the server room door is authorization.
  • The order is always authentication first, authorization second. If you don't know who someone is, you can't decide what to allow them.

Authentication and Authorization ​

AspectAuthenticationAuthorization
What it asksWho are you?What are you allowed to do?
How it checksPassword, OTP, fingerprint, tokenRole (admin/regular), permission list, ownership
HTTP status code on failure401 Unauthorized403 Forbidden
ExampleLoginOnly admins can delete posts, you can only edit your own posts

The name of 401 is "Unauthorized," so it is easy to get confused, but the real meaning is "not authenticated (we don't know who you are)." When the server knows who you are but you lack permission, it uses 403. Status codes are covered in more detail in the HTTP Status Codes article.

Method 1: HTTP Basic Authentication ​

The simplest method: every request carries the ID and password as is in a header.

Authorization: Basic MW1vOm15LXBhc3N3b3Jk

The MW1vOm15... part is ID:password converted to Base64. Base64 is not encryption but a simple character conversion, so anyone can turn it back into the original right away (we check this ourselves in the code below).

In a browser, it usually proceeds in the order below. When the server first says "an ID and password are required" with 401 and the WWW-Authenticate header, the browser shows an input dialog and sends the request again with the Authorization header attached.

HTTP Basic authentication flow: the server requests credentials with 401 and WWW-Authenticate, the client sends the request again with an Authorization header, and the server checks it and responds with 200 or 401

Image source: MDN, HTTP authentication (CC BY-SA 2.5)

  • Pros: very simple to implement, and since it is a standard, almost every tool supports it.
  • Cons: the password travels with every request, so it is very dangerous without HTTPS, and there is no concept of logging out.
  • Uses: only for internal tools, test servers, and simple admin pages.

Method 2: Session-Based Authentication ​

The password is checked only once at login, and after that the user is recognized by a session ID issued by the server. How it works is laid out in detail in the Cookies and Sessions article.

Login → server records {sessionID: user} in the session store → sends the session ID with Set-Cookie
Later requests → browser sends the session ID with Cookie → server looks up the user in the store
  • It is a stateful method, where the server holds the state.
  • Just deleting the session on the server logs the user out immediately, so it is easy to control.

Method 3: Token-Based Authentication ​

When login succeeds, the server issues a token, and the client sends that token in a header with every later request.

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Bearer means "grant permission to whoever holds this token." So if the token is stolen, the thief gets the same permissions.

There are two kinds of tokens.

KindWhat it looks likeHow the server checks it
Opaque tokenA meaningless random stringYou must look it up in a store to know whose it is (similar to a session)
Self-contained token (JWT)A string containing user info and a signatureOnly the signature needs checking, so no store lookup is needed

When the token itself contains the information, as with JWT, the server doesn't need to store user info separately, making it a stateless method.

Session-Based vs Token-Based ​

AspectSession-basedToken-based (JWT)
Where user info livesThe server's session storeInside the token (kept by the client)
Server stateYes (stateful)No (stateless)
Sent with each requestCookie: session_id=... (sent automatically)Authorization: Bearer ... (usually attached manually)
Scaling serversServers must share the session storeAny server can verify it as long as they share the secret key (or public key)
Forced logoutImmediately possible by deleting the sessionValid until it expires. Blocking it needs extra measures like a blocklist
Network costOnly a short ID travels in the cookieTokens are long, so each request carries more data
Good fitRegular websites, services where one server also renders the pagesMobile apps, services split across many servers (MSA), APIs opened to outsiders

Rather than one always being better, people often choose sessions when immediate control matters, and tokens when scalability and support for multiple clients matter. In practice, the two are sometimes mixed (e.g. putting a JWT in an HttpOnly cookie).

Method 4: API Key ​

A method used mainly when a program (an application), not a person, uses an API. Typical examples are services that issue you a key when you sign up, like public data APIs, map APIs, and AI model APIs.

How It Works ​

  1. The user gets an API Key issued by the service. (Like public-agency APIs, some require you to submit an application and get admin approval.)
  2. When calling the API, you send the key along. It usually goes in a header like X-API-Key: ... or in Authorization: Bearer ....
  3. Using the key, the server checks whose key it is, what permissions it has, and how much usage remains.
  4. Once verified, it returns the data.

Problems and Precautions ​

  • A single key is both an ID card and a key, so if it leaks, anyone can pretend to be its owner.
  • That is why keys need to be rotated regularly, but sometimes accidents happen during rotation where only one side gets updated and they no longer match.
  • If you put the key as is in frontend code or a GitHub repository, anyone can see it. It is safe to keep keys in server-side environment variables and have the browser call through your own server.
  • To reduce damage if a key is stolen, also apply allowed domain/IP restrictions, permission scope limits, and usage limits.
  • Putting the key in the URL query (?api_key=...) makes it likely to be left in server logs or browser history, so send it in a header when possible.

Method 5: OAuth 2.0 ​

Like "Log in with Kakao" or "Log in with Google," this is a way to give another app permission to use part of your information without telling it your password.

  • An API Key grants permission to "the program holding the key," but OAuth grants permission only within the scope the user directly agreed to.
  • Instead of a password, the app receives an Access Token and fetches only the data within the set scope.
  • OAuth is originally a set of rules for authorization (delegating permission). When it is used for "login that verifies who you are," OpenID Connect, built on top of it, is used.

The detailed flow is covered in the OAuth article.

Comparison by Method ​

MethodWhat is sentServer stateMainly used forWatch out for
BasicID:password (Base64)NoneInternal tools, testingHTTPS is a must, the password travels every time
SessionSession ID cookieYesRegular websitesSharing the store when scaling, CSRF defense
Token (JWT)Bearer tokenNoneMobile apps, API serversValid until expiry if stolen, storage location
API KeyThe issued keyOnly keeps a list of keysServer-to-server communication, public APIsReplace immediately if leaked, never put in code
OAuth 2.0Access TokenManaged by the authorization serverSocial login, external app integrationMinimize scope, use PKCE

Getting a Feel with Code: Base64 Is Not Encryption ​

Let's build a Basic authentication header and turn it back, and also write a simple function that checks an API Key.

python
import base64
import hmac

# Basic auth: convert "ID:password" to Base64 and send it in a header
token = base64.b64encode(b"1mo:my-password").decode()
print("Authorization: Basic " + token)

# But Base64 is not encryption, so anyone can turn it back right away
print(base64.b64decode(token).decode())

# API Key check: compare with the key the server stored (use a function that doesn't leak comparison time)
SAVED_KEYS = {"demo-key-1234": "1mo"}

def check_api_key(key):
    for saved, owner in SAVED_KEYS.items():
        if hmac.compare_digest(saved, key):
            return f"{owner}'s key, request allowed"
    return "401 Unauthorized"

print(check_api_key("demo-key-1234"))
print(check_api_key("wrong-key"))

Output:

Authorization: Basic MW1vOm15LXBhc3N3b3Jk
1mo:my-password
1mo's key, request allowed
401 Unauthorized
  • As in the second line, Base64 reveals the original password in one line. That is why Basic authentication requires HTTPS.
  • The reason for using hmac.compare_digest instead of == when comparing keys is that == compares from the first character and stops as soon as one differs, which makes possible an attack that figures out the key one character at a time from differences in response time (a timing attack). compare_digest always takes the same amount of time to compare.
  • In a real service, it is safer to store API Keys as hash values instead of the originals, just like passwords.

Interview Questions ​

Q. What is the difference between authentication and authorization? A. Authentication checks who the user is, and authorization checks whether the verified user has permission to access a specific resource. An authentication failure gets a 401 response, and an authorization failure gets a 403.

Q. What is the difference between session-based and token-based authentication? A. Sessions are a stateful method where the server stores the user's state and looks it up by session ID, while tokens (JWT) are a stateless method where user info and a signature are inside the token and the server verifies it without a store. Sessions make forced logout easy, and tokens make scaling servers easy.

Q. What are the downsides of the API Key method? A. A single key decides both identity and permissions, so if it leaks, it can be abused as is. You reduce the risk by rotating keys regularly, restricting allowed IPs and domains, limiting permission scope and usage, and keeping keys only in server environment variables.

Q. Why shouldn't you use Basic authentication without HTTPS? A. Base64 is encoding, not encryption, so anyone can turn it back into the original value, and since the password travels with every request, anyone snooping on the traffic sees the password right away.

Summary ​

ConceptOne-line summary
AuthenticationChecks who you are. 401 on failure
AuthorizationChecks what you are allowed to do. 403 on failure
Basic authenticationSends ID:password in Base64 every time. HTTPS required
Session-basedServer keeps the state, identified by a session ID cookie. Forced logout is easy
Token-basedSends the token as Bearer. With JWT, the server can verify it without knowing any state
API KeyA key issued for programs. Preparing for leaks is the key point
OAuth 2.0Delegated permission: use a token for the scope the user agreed to, instead of a password