Skip to content
notes.vinhnq.com

Search

SecuritySenior21 min read

Authorization, SSO and OAuth2: from RBAC to OpenID Connect

Review 19 cards
On this page

Backend security series: 1. Encoding, hashing, encryption and signatures · 2. Storing passwords and encrypting personal data · 3. Web attacks and the OWASP Top 10 · 4. Authentication: sessions, cookies and JWT · 5. Authorization, SSO and OAuth2

Authentication answers “who are you”; authorization answers “what may you do, and to which data” — and the OWASP Top 10 (2021) puts Broken Access Control at number one. After this post you can pick an authorization model, assess a cookie-based SSO design, and tell OAuth2 from OpenID Connect; JWT structure is in part 4.

1. Case study: plain RBAC

Key idea: RBAC (Role-Based Access Control) gives users roles, and the code says which roles may call which API. It’s simple, but every limitation comes from roles being hard-wired into code.

URL rules with hasRole, rule order, hasRole versus hasAuthority and a 403 page in a working app are in form login with Spring Security.

A flight system has admins, operations staff and customers:

CREATE TABLE app_user (user_id BIGINT PRIMARY KEY, username VARCHAR(64) NOT NULL UNIQUE);
CREATE TABLE role     (role_id BIGINT PRIMARY KEY, role_name VARCHAR(64) NOT NULL UNIQUE);
CREATE TABLE role_binding (
    user_id BIGINT NOT NULL REFERENCES app_user(user_id),
    role_id BIGINT NOT NULL REFERENCES role(role_id),
    PRIMARY KEY (user_id, role_id)
);

The token carries a "roles": ["ADMIN"] claim and the code declares roles per endpoint (Spring Security 6 needs @EnableMethodSecurity):

@PreAuthorize("hasAnyRole('ADMIN', 'OPERATOR')")
@PostMapping("/flights")
FlightDto create(@RequestBody @Valid CreateFlight cmd) { ... }

The slides list three limitations:

  • Overlapping roles: OPERATOR and SUPPORT differ by a single cancel-ticket right.
  • Role explosion: OPERATOR_HN, OPERATOR_READONLY… until you have hundreds of roles nobody dares delete.
  • Changes need a deploy: edit @PreAuthorize, then redeploy.

When roles travel through a JWT into Spring Security, the ROLE_ prefix is a common mistake:

Spring Security: hasRole, hasAuthority and the prefix

2. Case study: roles + permissions

Key idea: add one level — permission = resource + action (flights:create), role = a set of permissions. Code checks only permissions, so it stays stable; roles are data an admin changes at runtime.

A tested Spring version (permissions loaded from the database through a custom AuthorizationManager, combined with @PreAuthorize) is in rotating refresh tokens and permission-based authorization.

CREATE TABLE permission (permission_id BIGINT PRIMARY KEY, permission_name VARCHAR(128) NOT NULL UNIQUE);
CREATE TABLE permission_binding (
    role_id       BIGINT NOT NULL REFERENCES role(role_id),
    permission_id BIGINT NOT NULL REFERENCES permission(permission_id),
    PRIMARY KEY (role_id, permission_id)
);
-- A user's effective permissions
SELECT DISTINCT p.permission_name
FROM role_binding rb
JOIN permission_binding pb ON pb.role_id = rb.role_id
JOIN permission p          ON p.permission_id = pb.permission_id
WHERE rb.user_id = :userId;

The code says @PreAuthorize("hasAuthority('flights:create')") and never changes again. Letting SUPPORT cancel tickets is one INSERT INTO permission_binding.

Limitations: the finer the resources, the harder the permission list is to manage; and field-level control (see a flight but not its cost price) has no direct expression.

The course’s JWT example puts the permission list into the scope claim. That choice has a price:

What permissions in the token mean: a leaver can still call the API

3. Beyond roles and permissions

Key idea: a permission says “what kind of action”, not “on which object”. Ownership and tenant must be checked separately; rules based on attributes or relationships call for ABAC or ReBAC.

Object-level authorization. bookings:read says the user may read bookings, not which bookings. A GET /bookings/{id} that only checks the permission is an IDOR (Insecure Direct Object Reference — change the id in the URL and you read someone else’s data).

@GetMapping("/bookings/{id}")
@PreAuthorize("hasAuthority('bookings:read')")
BookingDto get(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) {
    return bookings.findByIdAndOwnerId(id, Long.parseLong(jwt.getSubject()))  // ownership lives in the query
            .map(BookingDto::from)
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}

Three ways to go further: multi-tenancy (every permission scoped to a tenant), ABAC (by attributes, such as branch or working hours) and ReBAC (by relationships, such as folder sharing). Field-level access belongs in the response layer; never rely on the frontend hiding a column.

Multi-tenancy, ABAC, ReBAC and field-level access

Multi-tenancy. In SaaS every permission is scoped to a tenant: role_binding gets a tenant_id, the token carries the active tenant, every query filters by it. PostgreSQL Row-Level Security (the DB filters rows by policy) makes a good second line of defence.

ABAC and ReBAC.

  • ABAC (Attribute-Based): “the Hanoi branch may only edit flights departing HAN, during working hours”. Usually moved into a policy engine such as Open Policy Agent or AWS Cedar.
  • ReBAC (Relationship-Based): sharing a parent folder grants access to the files inside. Built on the Google Zanzibar model; open-source options are OpenFGA and SpiceDB.
  • Field-level access usually belongs in the response layer: permission-specific DTOs, masked fields when a right is missing. Never rely on the frontend hiding a column.

4. Case study: Single Sign-On for two web apps

Key idea: SSO (sign in once, use many apps) via a parent-domain cookie works, but it trusts every subdomain and can’t cross to another domain. The standard answer: a central IdP holds the global session, and apps talk to it with OpenID Connect.

4.1. The problem and the slides’ design

Two web apps live at sub1.domain.com and sub2.domain.com and share one identity database. Requirements: (1) once U1 logs in on sub1, they are logged in on sub2; (2) in the same browser, U1 on sub1 and U2 on sub2 at the same time.

The slides’ design: App 1 doubles as the auth server and puts the token into a host-only cookie (sent back only to that exact host) for sub1.domain.com and a Domain=domain.com cookie (sent to every subdomain). App 2 receives the parent-domain cookie and asks App 1 whether the token is valid; each app prefers its own host-only cookie.

The slides’ cookie design step by step, cookie names and “two users at once”

When U1 logs in on sub1, App 1 puts the token into a host-only cookie for sub1.domain.com and a Domain=domain.com cookie:

Cookie for After U1 logs in After U2 logs in on sub2
domain.com token1_u1 token2_u2 (overwritten)
sub1.domain.com token1_u1 token1_u1
sub2.domain.com (none) token2_u2

When U1 opens sub2, the browser sends the domain.com cookie, App 2 asks App 1 “is this token valid”, and serves the resource once confirmed. When U2 logs in on sub2, each app follows one rule: prefer my own host-only cookie, fall back to the parent-domain cookie, so both users coexist.

If both cookies share a name, the browser sends both with no guaranteed order. So they need different names (sid_sub1, sid_shared) for the “prefer my own” rule to work at all.

Requirement (2) is odd too: SSO means one person signs in once. The real need is usually “switch account” or “admin impersonates user” (with an audit log). Both should be designed explicitly rather than resting on cookie precedence.

4.2. What’s right and what’s wrong

The cookie mechanics are right: a cookie without Domain is host-only, and a Domain=domain.com cookie goes to every subdomain. Outside the classroom there are three problems:

  • Every subdomain is trusted: it can read and overwrite the token.
  • One parent domain only: an app on otherbrand.com means starting over.
  • Apps are coupled: App 2 needs App 1 at runtime, and both read the same password table.

4.3. The standard answer: a central IdP + OpenID Connect

Move login into an Identity Provider (IdP — a service dedicated to sign-in: Keycloak, Auth0, Okta, Entra ID, Cognito). Only the IdP holds passwords, MFA and the global session; each app is a client with its own session and host-only cookie and never reads the identity database.

sequenceDiagram
    participant B as Browser
    participant A1 as App 1
    participant A2 as App 2
    participant IdP as IdP
    B->>A1: Open app 1, no session
    A1-->>B: Redirect to IdP with state and code_challenge
    B->>IdP: Enter password and MFA
    IdP-->>B: Set global session, redirect to App 1 with code
    B->>A1: Callback with code
    A1->>IdP: Exchange code for ID token and access token with code_verifier
    B->>A2: Open app 2, no session
    A2-->>B: Redirect to IdP
    IdP-->>B: Global session exists, redirect to App 2 with code

The second time there’s no password prompt because the browser already has a session at the IdP: that’s SSO, and it works across any domains. Logout is the hard part: ending one app’s session doesn’t end the IdP session.

OIDC’s three logout styles, and SAML 2.0
  • RP-initiated logout: the app redirects to the IdP’s end_session_endpoint to end the global session.
  • Back-channel logout: the IdP calls each app server-to-server with a signed logout_token. The most reliable option.
  • Front-channel logout: the IdP loads an iframe for each app. Increasingly unreliable as browsers block third-party cookies.

Large enterprises still use SAML 2.0: the same IdP idea, but exchanging signed XML assertions, which is heavy and easy to get wrong (XML signature wrapping). New systems should use OIDC; Keycloak can bridge both.

5. OAuth 2.0 and OpenID Connect

Key idea: OAuth 2.0 is delegation: a user lets a client call an API on their behalf with limited scope, and the result is an access token for the API. OpenID Connect is authentication on top of OAuth: it adds an ID token that tells the client who the user is.

It’s like giving a valet a spare key: the key starts the car, but it doesn’t prove the holder owns it. OIDC adds the openid scope, an ID token (always a JWT, carrying sub, iss, aud, nonce), and the userinfo and discovery endpoints.

Access token ID token
Audience Resource server (API) Client (app)
Answers What may be done (scope) Who the user is
Format JWT or opaque string Always a JWT

Grant types (the ways a client asks for a token):

  • Authorization code + PKCE for every user-facing app. The client sends code_challenge = SHA256(code_verifier) and later the verifier when exchanging the code, so an intercepted code is useless. state protects the callback against CSRF.
  • Client credentials for service-to-service calls; refresh token (rotated for public clients); device code for TVs and CLIs.
  • Implicit and password grants are deprecated (RFC 9700).

Spring Boot 3: a web app uses .oauth2Login(...), an API is a resource server, service-to-service calls use client_credentials.

Spring Boot 3 setup: oauth2Login, resource server, client credentials

A web app logging in through an IdP: declare spring.security.oauth2.client.registration.<id> and provider.<id>.issuer-uri, enable .oauth2Login(...), and use OidcClientInitiatedLogoutSuccessHandler so logout also ends the IdP session.

An API accepting tokens: set spring.security.oauth2.resourceserver.jwt.issuer-uri. Spring fetches the JWKS and checks signature, iss and exp (add a validator for aud):

@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
            .authorizeHttpRequests(a -> a
                    .requestMatchers(HttpMethod.POST, "/flights").hasAuthority("SCOPE_flights:create")
                    .anyRequest().authenticated())
            .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))   // scope -> SCOPE_*
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .build();
}

Service-to-service: register a client_credentials grant and let OAuth2AuthorizedClientManager fetch, cache and renew tokens. Since Spring Security 6.4, plug it into RestClient with OAuth2ClientHttpRequestInterceptor. Don’t cache tokens in a static field yourself.

Exercises

Homework: JWT + permission-based authorization

The task (paraphrased): authenticate with JWT and authorize with roles + permissions. Users and permissions can be hard-coded (a map from username to a list of permissions). A login API returns a JWT containing the username, user id and scope. Each protected API declares the permission it needs; on each request, verify the token and then the permission.

Solution idea (plain JDK 21): pin HS256 (never trust the alg header), compare signatures with MessageDigest.isEqual, and return 404 for undeclared routes (deny by default). 401 means “I don’t know who you are”; 403 means “I know who you are, and you can’t do this”.

JDK 21 solution: code, test run and senior improvements

HS256 with javax.crypto.Mac, a server on com.sun.net.httpserver, and a route table declaring permissions.

record User(long id, String password, List<String> permissions) {}
record Route(String method, String path, String permission) {}
record Principal(long userId, String username, Set<String> scopes) {}

static final Map<String, User> USERS = Map.of(
        "alice", new User(1, "alice-pw", List.of("flights:create", "flights:list")),
        "bob",   new User(2, "bob-pw",   List.of("flights:list")));
static final List<Route> ROUTES = List.of(
        new Route("GET", "/flights", "flights:list"), new Route("POST", "/flights", "flights:create"));

// issue(): payload {iss, sub, username, user_id, scope: "a b", iat, exp = iat + 600},
// token = b64url(header) + "." + b64url(payload) + "." + b64url(hmac(...))
static Optional<Principal> verify(String token, long now) {
    String[] parts = token.split("\\.");
    if (parts.length != 3 || !decode(parts[0]).contains("\"alg\":\"HS256\"")) return Optional.empty();
    if (!MessageDigest.isEqual(hmac(parts[0] + "." + parts[1]), B64D.decode(parts[2]))) return Optional.empty();
    Map<String, String> claims = parseClaims(decode(parts[1]));
    if (!ISSUER.equals(claims.get("iss")) || now >= Long.parseLong(claims.get("exp"))) return Optional.empty();
    return Optional.of(new Principal(Long.parseLong(claims.get("user_id")), claims.get("username"),
            Set.of(claims.get("scope").split(" "))));
}

static void api(HttpExchange ex) throws IOException {
    var route = ROUTES.stream().filter(r -> r.method().equals(ex.getRequestMethod())
            && r.path().equals(ex.getRequestURI().getPath())).findFirst();
    if (route.isEmpty()) { send(ex, 404, "not_found"); return; }
    String auth = ex.getRequestHeaders().getFirst("Authorization");
    if (auth == null) { send(ex, 401, "missing_token"); return; }
    var p = auth.startsWith("Bearer ")
            ? verify(auth.substring(7), Instant.now().getEpochSecond()) : Optional.<Principal>empty();
    if (p.isEmpty()) { send(ex, 401, "invalid_token"); return; }          // with WWW-Authenticate: Bearer
    if (!p.get().scopes().contains(route.get().permission())) { send(ex, 403, "insufficient_scope"); return; }
    send(ex, 200, "ok " + p.get().username());
}

Running java AuthzServer.java (JDK 21); main walks through the cases with HttpClient (“forged scope” means bob added flights:create to the payload and kept the old signature):

POST /login   alice             -> 200 {"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3...
POST /login   wrong pw          -> 401 invalid_credentials
GET  /flights no token          -> 401 missing_token
GET  /flights bob               -> 200 ok bob
POST /flights bob               -> 403 insufficient_scope
POST /flights alice             -> 200 ok alice
POST /flights bob forged scope  -> 401 invalid_token
GET  /flights expired           -> 401 invalid_token
GET  /nope    alice             -> 404 not_found

The payload is just Base64url, so bob can read and edit it, but the old signature no longer matches.

What a senior would improve:

  • A secret of at least 256 bits from a secret manager with a kid for key rotation, or RS256/ES256 so other services only need the public key.
  • Passwords hashed with Argon2id or bcrypt (part 2).
  • A proven JWT library (Nimbus) instead of hand parsing; checks for aud, nbf and clock skew.
  • Permissions loaded from the DB with the schema in section 2; and ownership checks.
The same homework in Spring Security 6

Written from the documentation, not run. Login signs the token with a JwtEncoder (NimbusJwtEncoder with an ImmutableSecret), and verification is the resource server setup from section 5:

var claims = JwtClaimsSet.builder()
        .issuer(ISSUER).subject(String.valueOf(user.id()))
        .issuedAt(now).expiresAt(now.plus(Duration.ofMinutes(10)))
        .claim("username", user.username()).claim("user_id", user.id())
        .claim("scope", String.join(" ", user.permissions())).build();
String token = jwtEncoder.encode(JwtEncoderParameters.from(
        JwsHeader.with(MacAlgorithm.HS256).build(), claims)).getTokenValue();

@PreAuthorize("hasAuthority('SCOPE_flights:create')")
@PostMapping("/flights")
FlightDto create(@RequestBody @Valid CreateFlight cmd) { ... }

By default JwtGrantedAuthoritiesConverter splits the scope claim into SCOPE_... authorities. To read another claim or change the prefix, configure it inside a JwtAuthenticationConverter.

Exercise 2: SSO when an app lives on another domain

A third app arrives at partner-portal.com. Why does the parent-domain cookie design break, and what replaces it?

Solution to exercise 2

Cookies for domain.com are never sent to partner-portal.com.

The replacement: run Keycloak at sso.domain.com with three clients (exact-match redirect URIs), authorization code + PKCE, each app’s own session in a host-only __Host-SESSION cookie. APIs are resource servers checking iss and aud, with back-channel logout enabled. User data moves to the IdP; apps keep only the IdP sub as the link key.

Remember

  • Can you explain why checking permissions is more stable than checking roles in code?
  • Do you know why hasAuthority('bookings:read') isn’t enough, and how a query condition fixes the IDOR?
  • Can you weigh permissions in the JWT against per-request lookup, and say how to revoke access fast?
  • Can you name three weaknesses of parent-domain-cookie SSO and redraw the IdP + OIDC + PKCE flow?
  • Can you tell an access token from an ID token: who uses it, which question it answers?

Interview questions

Junior

How does authentication differ from authorization?

Authentication establishes who you are; authorization decides what you may do to which resource, and runs after authentication.

At the airport: the security checkpoint checks your ID, the gate checks your boarding pass. In HTTP: missing or invalid identity is 401, valid identity without the right is 403.

What is RBAC and where does it fall short?

Users are assigned roles and each feature allows some roles. Simple and easy to explain.

It falls short with overlapping roles, role explosion when you need fine distinctions, and, if roles are checked directly in code, every access change needs a redeploy.

What is SSO?

Sign in once, use many applications.

An identity provider holds a global session; a second app redirects the user to the IdP, which sees they’re already signed in and returns straight away. The common protocols are OpenID Connect and SAML.

Mid

Why check permissions rather than roles in code?

Permissions (flights:create) map to features, so they’re stable; roles are sets of permissions stored in the DB, so they can change at runtime.

Granting a role a new right is a row of data rather than a deploy, and role explosion stays out of the code.

How does OAuth 2.0 differ from OpenID Connect?

OAuth is delegation; OIDC is authentication built on OAuth. Use the ID token for login and the access token for API calls.

OAuth: a client calls an API on a user’s behalf with limited scope, and gets an access token meant for the resource server. OIDC adds the openid scope and an ID token (a JWT) telling the client who the user is.

Why does the authorization code flow need PKCE?

Because the code travels through a browser redirect and can be intercepted; PKCE makes an intercepted code useless.

The code can leak through a malicious app registering the same URL scheme, or through logs. PKCE makes the client send SHA256(code_verifier) up front and the verifier when exchanging the code; a stolen code without the verifier gets no token. OAuth 2.1 requires PKCE for every client.

Senior

GET /bookings/{id} already has hasAuthority('bookings:read'). What’s missing?

An object-level check: a user who changes the id reads someone else’s booking (an IDOR, part of A01 Broken Access Control).

Put the ownership or tenant condition into the query, return 404 when nothing matches, and keep a test where user A requests user B’s id.

Should permissions live in the JWT or be looked up per request?

Combine them: 5–15 minute access tokens with coarse permissions, sensitive actions re-checked against the source of truth.

In the token there’s no DB call, but tokens grow and permissions only update when the token expires. Per-request lookup (with a short-TTL cache) keeps tokens small and revocation fast, at the cost of latency. Also: re-check permissions on refresh, and keep a deny list by sub/jti for emergencies.

What does logout involve in an SSO system?

Three things: per-app sessions, the IdP’s global session, and the tokens already issued.

Ending an app session without ending the IdP session just signs the user straight back in. Use RP-initiated logout for the IdP session, back-channel logout to notify the other apps, short-lived access tokens, and refresh token revocation.

Useful phrases for interviews

  • “Authentication tells us who you are; authorization decides what you can do, and to which data.”
  • “Our code checks permissions, never role names, so access changes are data changes rather than deploys.”
  • “A permission says you may read bookings; an ownership check says you may read this booking.”
  • “Putting permissions in the token trades revocation speed for fewer lookups.”
  • “Sharing a cookie on the parent domain puts every subdomain inside the trust boundary.”
  • “OAuth is delegation; OpenID Connect adds authentication with the ID token.”
  • “Every user-facing client uses the authorization code flow with PKCE.”
  • “Logout in SSO has to end the IdP session too, ideally with back-channel logout.”
  • “We return 401 when we don’t know who you are and 403 when we do but you lack the permission.”

Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.