Authentication and authorization: RBAC, JWT, OAuth, OIDC, SSO

Every system design needs two answers: who is making this request, and what are they allowed to do? The first is authentication (authn), the second is authorization (authz). Interviews mix many terms here (JWT, OAuth, OIDC, SSO, RBAC), and people often confuse them. This lesson explains what each one is for.

1. Authentication and Authorization

  • Authentication: proving who you are, with a password, a one-time code, a fingerprint or a token. Failure returns 401 Unauthorized.
  • Authorization: deciding what you may do once we know who you are. Failure returns 403 Forbidden.

Our example is a company expense app. Employees submit expenses, managers approve them, and finance pays them. A new employee logs in (authentication), then tries to approve a colleague's expense and is refused (authorization). A third-party tax tool also wants to read expense reports, which brings in OAuth. We will follow this one app through the lesson.

2. Passwords, Sessions and Tokens

2.1 Storing Passwords

Never store a password, and never store a plain fast hash such as SHA-256, because attackers can test billions of guesses per second against it. Store the output of a deliberately slow, salted password hash such as bcrypt, scrypt or Argon2.

  • Salt: a random value created for each user and stored next to the hash. The hash is computed from the salt plus the password, so two users with the same password get different hashes, and one precomputed table of common passwords (a rainbow table) cannot be used against all users. At login, the server reads the user's salt, hashes the typed password with it, and compares the result. The salt is not secret.
  • Cost: choose it so one check takes roughly 100 ms. That is not noticeable to a user but makes mass guessing expensive.
  • Multi-factor authentication: a second proof, such as an app code or a hardware key, stops most stolen-password attacks.

2.2 Sessions Against Tokens

After login, the client must prove who it is on every request. There are two ways.

  • Server-side session: the server creates a random session ID, stores the user data under it (in Redis, for example), and sends the ID in a cookie. Each request looks up the ID. Logout and revocation are instant: delete the entry. The cost is a lookup per request and a shared session store.
  • Token (stateless): the server signs a token that contains the user's identity. Any server can verify the signature without a lookup. The cost is that a token is hard to revoke before it expires.

For browser cookies, set HttpOnly (JavaScript cannot read it, which limits theft through XSS), Secure (HTTPS only) and SameSite=Lax or Strict (the browser does not send it on cross-site requests, which blocks most CSRF attacks).

3. JWT

3.1 How a JWT Is Built

A JSON Web Token is the usual format for signed tokens. It has three parts joined by dots: header.payload.signature, each encoded with base64url. The payload holds claims:

{
  "iss": "https://login.example.com",
  "sub": "user-8841",
  "aud": "expense-api",
  "exp": 1790000900,
  "iat": 1790000000,
  "scope": "expenses.read expenses.write",
  "team": "finance-eu"
}

Here iss is who issued the token, sub the user, aud the service it is meant for, and exp the expiry time (a Unix timestamp). The signature proves that the content was not changed. Important points:

  • Signed, not encrypted. Anyone can read the payload. Never put passwords or private data in it.
  • Signing algorithms. HS256 uses one shared secret, so every service that verifies could also forge tokens. RS256 or ES256 use a private key to sign and a public key to verify. The authorization server publishes its public keys at a URL (a JWKS endpoint), and every service verifies tokens on its own without calling the authorization server. This is why asymmetric keys are the choice for microservices.
  • Always validate the signature, exp, iss and aud, and accept only the algorithms you expect (a known attack uses "alg": "none" to skip the signature).

3.2 The Revocation Problem

A signed token is valid until it expires, even if the user is fired or the token is stolen. The standard solution is two tokens:

  • Access token: a short-lived JWT, usually 5 to 15 minutes, sent with each API call.
  • Refresh token: a long-lived random value (days to weeks) kept in a database. The client sends it to the authorization server to get a new access token. The server can revoke it at any time, and it is rotated: each use returns a new refresh token and invalidates the old one, so a stolen one is detected when both are used.

For instant revocation, services can check a small denylist of revoked token IDs (kept in Redis), which brings back a lookup.

3.3 Session or JWT

Server-side session JWT access token
Verification Lookup in a session store Signature check, no lookup
Revocation Instant Only at expiry, unless a denylist is used
Scaling across services All need the shared store All need only the public key
Size Small ID Larger, sent on every request
Best for One web app with a browser APIs, mobile apps, many services

4. OAuth 2.0: Delegated Access

OAuth answers a different question: how can an app act for a user without getting the user's password? The tax tool (TaxHelper) wants to read a user's expense reports. Instead of asking for the password to the expense app, it sends the user to the expense app to approve a limited permission. TaxHelper then gets a token that can only do that.

The four roles are: the resource owner (the user), the client (TaxHelper), the authorization server (issues tokens) and the resource server (the expense API). The permission is expressed as a scope, such as expenses.read.

4.1 Authorization Code Flow with PKCE

This is the flow to use for web apps, single-page apps and mobile apps.

sequenceDiagram
    participant U as User (browser)
    participant C as Client (TaxHelper)
    participant A as Authorization server
    participant R as Resource server (expense API)
    C->>U: Redirect to the authorization server (scope, code_challenge)
    U->>A: Open the login page, user logs in and approves the scope
    Note over A: Saves the code_challenge with the code it issues
    A->>U: Redirect back with a one-time code
    U->>C: Deliver the code
    C->>A: Exchange code plus code_verifier (direct call)
    Note over A: Hashes the code_verifier and compares it with the saved code_challenge
    A-->>C: Access token (and refresh token)
    C->>R: API call with the access token
    R-->>C: Expense data

The code travels through the browser, where it could be stolen. PKCE (Proof Key for Code Exchange) makes a stolen code useless. The steps are:

  1. The client creates a random code_verifier and keeps it to itself. It computes the hash of the verifier, called the code_challenge.
  2. The client sends only the code_challenge to the authorization server, as part of the login redirect. It passes through the browser, but a hash cannot be turned back into the verifier.
  3. The authorization server saves the code_challenge together with the one-time code it issues.
  4. When the client exchanges the code, it sends the original code_verifier straight to the authorization server, not through the browser. The authorization server hashes it and compares the result with the saved code_challenge. If they match, it issues the tokens.

An attacker who steals the code from the browser does not have the verifier, so the exchange fails. Only the client that started the flow can finish it. PKCE is required for apps that cannot keep a secret (browser and mobile apps) and recommended for all.

The client also sends a random state value in the login redirect and checks that the same value comes back in the callback. This stops an attacker from tricking the browser into completing a login the user never started (cross-site request forgery on the callback).

4.2 Client Credentials Flow

When there is no user, such as one backend service calling another, the service authenticates with its own ID and secret and receives an access token for itself. It replaces long-lived shared passwords between services.

The implicit flow and the password grant are deprecated. Do not propose them.

5. OpenID Connect (OIDC): Login on Top of OAuth

OAuth gives an app a token to call APIs, but it does not say who the user is. OpenID Connect adds that, through an OIDC provider (also called the identity provider, or IdP). Rule of thumb: OAuth is for authorization, OIDC is for authentication. "Sign in with Google" is OIDC.

5.1 What OIDC Adds

OIDC uses the same authorization code flow with PKCE from the previous section. Three things change:

  • The app adds the scope openid to the request. Other standard scopes ask for more details: profile (name) and email. The scope offline_access asks for a refresh token.
  • The token response contains an ID token next to the access token (and the refresh token, if requested).
  • The provider has a UserInfo endpoint. The app calls it with the access token to get more details about the user.

5.2 The ID Token

The ID token is a JWT that says who just logged in, and for which app:

{
  "iss": "https://login.example.com",
  "sub": "user-8841",
  "aud": "expense-app-web",
  "exp": 1790000900,
  "iat": 1790000000,
  "nonce": "n-0S6_WzA2Mj",
  "email": "asha@example.com",
  "email_verified": true,
  "name": "Asha Rao"
}

Before trusting it, the app must check:

  • The signature, using the provider's public keys (from its JWKS address).
  • iss is the provider you expect.
  • aud is your own client ID. This proves the token was issued for your app and not for another one.
  • exp has not passed.
  • nonce is the same random value your app sent at the start of this login. This stops an attacker from replaying an old ID token.

After the checks, the app creates its own session (for example a session cookie). The ID token is proof of the login, not the session itself, so the app does not send it to every API call. Identify the user by the pair (iss, sub), not by email, because emails can change or be reused.

6. Single Sign-On (SSO)

An employee uses the expense app, the HR system, the wiki and the ticketing tool. Without SSO, each has its own password. With SSO, one central identity provider (IdP) such as Okta, Microsoft Entra ID, Keycloak or Auth0 handles login for all of them. Each app redirects to the IdP. If the user already has a session there, the IdP sends them straight back with a token, with no new password prompt.

6.1 How It Works

  1. The user opens the expense app. It has no session for them, so it redirects the browser to the IdP (this is the OIDC login from the previous section).
  2. The user logs in at the IdP, with a password and MFA. The IdP creates its own session and sets a cookie for its own domain.
  3. The IdP sends the user back with a code, and the app finishes the flow and creates its own session.
  4. Later the user opens the HR system. It redirects to the IdP, which sees the existing IdP session and returns immediately, with no prompt.

So there are two kinds of sessions: one at the IdP, and one in each app. The apps never see the password. They trust the IdP's signed token (federation).

6.2 OIDC or SAML

  • OIDC uses JSON and JWTs, and suits web, mobile and single-page apps. It is the choice for new systems.
  • SAML uses signed XML assertions carried through the browser. It is older, common in enterprise software, and a poor fit for mobile apps and APIs.

For your own product, you usually should not build the login system yourself. Use a managed IdP or an open-source one such as Keycloak, and let your services only verify tokens.

7. Authorization Models

Authentication tells you who. Now decide what they can do.

7.1 The Four Models

Model Decision based on Expense app example Weakness
Access Control List (ACL) A list on each object Report 17 can be read by Asha and Ben Hard to manage at scale
Role-based access control (RBAC) The user's roles, each with permissions Employee: submit. Manager: approve. Finance: pay Roles multiply; cannot express "own team only"
Attribute-Based Access Control (ABAC) Rules over user, resource and context attributes Manager can approve if the expense is from their team and under 1,000 Rules are harder to audit and test
Relationship-Based Access Control (ReBAC) Relationships in a graph Can approve if "manager of" the submitter Needs a dedicated relationship store

RBAC is the default answer: simple and easy to explain. Real systems then add attribute or relationship checks for the details. ReBAC is used for sharing models such as folders and documents (Google's Zanzibar system and open-source tools like OpenFGA and SpiceDB follow it). Keep the policy separate from the business code where you can, so it can be changed and audited in one place.

7.2 Example in Spring Boot

The expense API is a resource server. It verifies the JWT using the issuer's public keys (found from the issuer URL), so it never calls the authorization server per request:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://login.example.com
@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                        .requestMatchers("/actuator/health").permitAll()
                        .anyRequest().authenticated())            // 401 without a valid token
            .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
        return http.build();
    }
}

@RestController
public class ApprovalController {

    private final ExpenseRepository repo;

    public ApprovalController(ExpenseRepository repo) {
        this.repo = repo;
    }

    @PostMapping("/expenses/{id}/approve")
    @PreAuthorize("hasAuthority('SCOPE_expenses.approve')")       // coarse check: 403 if missing
    public void approve(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) {
        Expense expense = repo.findById(id).orElseThrow();
        boolean ownTeam = expense.getManagerId().equals(jwt.getSubject());
        boolean withinLimit = expense.getAmountCents() <= 100_000;
        if (!ownTeam || !withinLimit) {                           // fine check on this exact object
            throw new AccessDeniedException("Not allowed to approve this expense");
        }
        expense.approve();
        repo.save(expense);
    }
}

There are two layers: the scope or role check says the caller may use this kind of action at all, and the object check says they may do it to this record. Forgetting the second check lets any user read or change any record by guessing IDs, a very common flaw called broken object-level authorization (BOLA, also called IDOR).

8. Where to Check in a Distributed System

  • At the edge: the API gateway (see the gateway lesson) validates the token, rejects bad ones early, and may apply coarse rules.
  • In every service: each service still verifies the token (or a signed internal identity) and makes its own authorization decision. Do not trust a request only because it came from inside the network. This is the "zero trust" approach.
  • Pass identity along: forward the user's token downstream so services know on whose behalf the call is made. With no user, use the client credentials flow.
  • Service-to-service transport: mutual TLS (see the TLS lesson) proves which service is calling. Tokens say what it may do.
  • Third-party API clients: an API key identifies a client app (store only its hash). OAuth is better when the call acts for a user.

9. Common Pitfalls

  • Authentication without authorization: any logged-in user can see any record.
  • Checks only in the UI or gateway, not in the owning service.
  • Fast hashes or plaintext passwords.
  • Long-lived JWTs with no refresh or revocation plan.
  • Not validating iss, aud or the algorithm.
  • Private data in a JWT payload, which is only encoded, not encrypted.
  • Tokens in localStorage, which any XSS script can read. Prefer an HttpOnly cookie for browser apps.
  • Using OAuth alone for login, instead of OIDC.
  • Role explosion: hundreds of near-identical roles. Add attribute rules instead.

10. Interview Questions This Lesson Prepares You For

  • What is the difference between authentication and authorization? Authentication proves who you are (401 on failure). Authorization decides what you may do (403 on failure).
  • Session or JWT? Sessions give easy revocation but need a shared store. JWTs verify without a lookup and suit APIs and many services, but are hard to revoke, so keep them short-lived with rotating refresh tokens.
  • How does a JWT work, and how do services verify it? Header, payload and signature. The authorization server signs with a private key. Services verify with the public key from the JWKS endpoint and check exp, iss and aud.
  • Explain OAuth 2.0 and the authorization code flow. It lets an app act for a user without the password. The user approves scopes at the authorization server, the app exchanges a one-time code (plus the PKCE verifier) for tokens, and calls the API with the access token.
  • What is the difference between OAuth and OIDC? OAuth gives access to APIs. OIDC adds an ID token to say who logged in.
  • How does SSO work? Apps redirect to a central identity provider using OIDC or SAML. An existing session there signs the user in with no new password.
  • RBAC or ABAC? Start with RBAC for simplicity, and add attribute or relationship rules where roles are not enough, such as "own team only" or an amount limit.
  • How do you secure service-to-service calls? Mutual TLS for the transport and short-lived tokens from the client credentials flow, with each service checking authorization itself.