System Design Part 8 Security

Authorization Models and the OWASP API Top 10: What You Can Do After Logging In

Bill.Lin 20 min read

System Design series Part 8-2 | Previous: Authentication: Sessions, Tokens, and OAuth 2.0/OIDC | Next: After BOLA Gets Past the BFF: Identity Propagation Between Microservices | Series map

Read first: Part 5-1 REST, gRPC, and GraphQL, Part 8-1 Authentication: Sessions, Tokens, and OAuth 2.0/OIDC.

Scenario and problem

The previous post settled “who sent this request”. After the talk platform went live, a security assessment reported four problems, and every one of the requests carried a valid logged-in identity:

  1. A member changed /v1/registrations/1001 in the URL to 1002 and saw someone else’s sign-up details, phone number, and payment status
  2. A member called GET /admin/lectures/42/registrations/export directly and downloaded the attendee list for the whole talk. The frontend did not show this button, but the API did not check
  3. When updating their profile, a member added "role": "ADMIN" to the JSON; when signing up, they added "status": "CONFIRMED" and skipped payment
  4. The attendee list API of the speaker panel returned each attendee’s full email and phone number. The frontend showed only names, but everything was in the response
The identity is right, but nobody checked what it may do1 / 4
The identity is right, but nobody checked what it may doMemberPlatform APISign-up dataAdmin APISpeaker panelMemberPlatform APISign-up dataChange to 1002Query 1002Sees someone else's sign-upMemberAdmin APIExport attendeesNo button, no API checkMemberPlatform API+ role: ADMINAccepts it allSpeaker panelPlatform APIAttendee listReturns full email and phone
  1. Change one numberThe member changes /v1/registrations/1001 in the URL to 1002 and sees someone else's sign-up, phone number, and payment status.
  2. An admin feature the frontend hidesThe member calls /admin/lectures/42/registrations/export directly and downloads the attendee list for the whole talk. The frontend does not show this button, but the API does not check.
  3. One extra fieldWhen updating their profile, the member adds "role": "ADMIN" to the JSON; when signing up, they add "status": "CONFIRMED" and skip payment.
  4. Returning too muchThe attendee list API of the speaker panel returns each attendee's full email and phone number. The frontend shows only names, but everything is in the response.

These four problems are numbers 1, 5, and 3 of the OWASP API Security Top 10 (2023), and none of them is an authentication problem: the identity is right, but nobody checked whether this identity is allowed to do this.

The simplest approach and its limits

Check roles on the controller:

java
@PreAuthorize("hasRole('MEMBER')")
@GetMapping("/v1/registrations/{id}")
public RegistrationView get(@PathVariable long id) {
    return registrationService.get(id);       // any member can read any record
}

A role answers “what kind of thing can this person do”: members can look up sign-ups. It does not answer “which record can this person do it to”: a member can look up only their own sign-ups. Problem 1 comes from exactly this gap.

Another common approach is “the frontend shows only the buttons you have permission for”. That is only the user interface; an attacker calls the API directly. Problem 2 comes from exactly this.

Core mechanism

Three levels of authorization

Level Question Example Matching OWASP API risk
Function level Can you call this operation? Only platform admins can export the list API5 Broken Function Level Authorization (BFLA)
Object level Can you perform this operation on this particular record? Members can see only their own sign-ups; speakers can see only the lists for their own talks API1 Broken Object Level Authorization (BOLA)
Property level Which fields of this record can you read and write? Speakers can see attendees’ names but not their phone numbers; members cannot change their own role or sign-up status API3 Broken Object Property Level Authorization (BOPLA)

You need all three. The function level is usually the easiest (one rule covers a whole group of APIs). The object level is the easiest to miss, because it needs to know who the data belongs to, and that information lives in the database, not in the token.

Authorization models

Model Form of the rule Example from the talk platform Good for Limits
RBAC (roles) Roles have permissions; users have roles PLATFORM_ADMIN can export the list The function level, job functions within an organization The object level needs separate handling; once requirements get detailed, the number of roles explodes (“speaker assistant for the Taipei region”)
ABAC (attributes) Decide from attributes of the user, the resource, and the environment A company admin can see sign-ups whose tenant_id equals their own company; exports allowed only during working hours Rules that combine attributes, multi-tenancy Rules are scattered and hard to review; “who can access this record” is hard to work out in reverse
ReBAC (relationships) Derive from relationships between entities Speaker 7 is the owner of talk 42; talk 42 belongs to company A; company A’s admins can see all of company A’s talks Sharing, hierarchy, delegation (“give an assistant co-management of this talk”) Relationship data has to be maintained and synced separately

The best-known ReBAC system is Google’s Zanzibar: the paper describes it serving hundreds of Google services with a unified relationship data model, handling more than 10 million checks per second with 95th-percentile latency under 10 milliseconds. Open-source implementations include OpenFGA and SpiceDB; AWS’s Cedar is a policy language that can express both RBAC and ABAC.

In practice the three are often mixed: RBAC for the function level, the simplest relationship, “owner”, for the object level, and a dedicated ReBAC system only once sharing and hierarchy requirements appear.

Where the authorization check goes

flowchart LR
    C[Client] --> G[API Gateway<br/>checks token and scope, rate limits]
    G --> S1[Sign-up service<br/>object and property levels]
    G --> S2[Talk service<br/>object and property levels]
    S1 -.optional.-> P[(Policy service<br/>OPA, Cedar, OpenFGA)]
    S2 -.optional.-> P
  • The gateway does coarse-grained checks: whether the token is valid, whether the scope allows calling this group of APIs, rate limiting. It does not know who sign-up 1002 belongs to
  • Each service does its own object-level and property-level checks: the data is in the service, so the decision can only be made there. If you rely only on the gateway’s checks, an attacker who bypasses the gateway (calling directly from the internal network) meets no protection at all (Monolith vs Microservices)

The decision logic can be embedded in the service, or centralized in a policy service (PDP, policy decision point), with the service only enforcing the decision (PEP, policy enforcement point). Centralizing gives you consistent policies and one place to audit them; the cost is that every decision has to send along the data it needs (“who owns sign-up 1002”), or the relationship data has to be synced to the policy service.

Lists are the biggest cost: for a page of 50 items, a remote check per item at 2 milliseconds each adds up to 100 milliseconds when run one after another. So list authorization is usually not “query first, then check each item”. Instead you put the authorization condition into the query itself, or first ask the policy service “which IDs can this user see” and then query with those IDs.

Object level: put the authorization condition into the query

sql
-- Wrong: query first, then check (or forget to check)
SELECT * FROM registration WHERE id = :id;

-- Right: ownership is part of the query condition
SELECT * FROM registration WHERE id = :id AND member_id = :currentMemberId;
  • currentMemberId can come only from the verified identity, never from the URL, query parameters, or request body. If a memberId from the request is used as a query condition, an attacker changes one number and gets someone else’s data
  • Return 404 when nothing is found, not 403. A 403 tells the attacker “this record exists, you just cannot see it”, which can be used for enumeration
  • Unpredictable IDs do not replace authorization: UUIDs make IDs hard for attackers to guess, but IDs show up in URLs, logs, and share links (Distributed IDs)
  • Every read path needs the same condition: lists, search (Full-Text Search and Inverted Indexes), caches (Caching in Depth), pagination cursors (Indexes and B+Trees), exports, real-time push subscriptions (Real-Time Updates), file downloads (File and Object Storage)
  • Multi-tenancy: every row of an enterprise customer’s data carries a tenant_id, and every query adds the tenant condition taken from the token. Sharding or routing to the right database is not authorization (Sharding)

Property level: list the allowed fields explicitly

  • Input: each operation has its own request object, containing only the fields that may be changed. If you bind the request straight to the entity, fields such as role, status, and price may get written along with it (mass assignment)
  • Output: return a different response object depending on the role. “Not shown by the frontend” does not mean “not returned”; anyone can see the response in the browser’s developer tools

Freshness of authorization data

  • After a role is revoked, the scopes and roles in the access token from the previous post stay valid until it expires. High-risk operations (exports, refunds, permission management) should look up the current permissions instead of looking only at the token
  • If permission checks read from a replica, a permission that was just revoked may still be in effect during the replication lag (Replication and Replication Lag)
  • Permission caches need short expiry times, or active invalidation when permissions change

Mapping to the OWASP API Security Top 10 (2023)

No. Risk Example from the talk platform Where in this series
API1 Broken Object Level Authorization Changing the sign-up ID to see someone else’s data This post; propagation between microservices in 8-3
API2 Broken Authentication Credential stuffing, a token whose aud is not verified Authentication: Sessions, Tokens, and OAuth 2.0/OIDC
API3 Broken Object Property Level Authorization Sending "status": "CONFIRMED"; a response that includes attendees’ phone numbers This post
API4 Unrestricted Resource Consumption pageSize=1000000, uploading a 10 GB file, triggering a flood of emails Rate Limiting, File and Object Storage
API5 Broken Function Level Authorization A member calling the admin export API This post
API6 Unrestricted Access to Sensitive Business Flows Bots grabbing every seat the moment sign-ups open, mass reservations that are never paid 8-5 Abuse Prevention, Sagas and the Outbox Pattern
API7 Server Side Request Forgery A webhook URL entered by a speaker points at an internal service This post
API8 Security Misconfiguration Actuator endpoints open to the outside, CORS allowing any origin, error messages containing stack traces 8-4, Observability
API9 Improper Inventory Management An old /v1 API without the new authorization checks is still online Versioning in REST, gRPC, and GraphQL
API10 Unsafe Consumption of APIs Fully trusting responses from payment or third-party APIs Timeouts, Retries, Backoff, and Jitter; validate external responses

Three of the top five are about authorization.

SSRF: making the server send requests for the attacker

A speaker can set a webhook URL. When there is a new sign-up, the platform calls that URL to notify the speaker’s own system. An attacker sets the URL to:

  • http://169.254.169.254/latest/meta-data/iam/security-credentials/: the cloud host’s metadata service, which may return the host’s temporary credentials. AWS IMDSv2 requires getting a session token with PUT first and can limit the response hop count to 1, which blocks most SSRF that can only send GET, but you still need defenses at the application layer
  • http://payment.lectures.svc.cluster.local/v1/refunds: the name of an internal service (Service Discovery); such services often assume “whoever calls me is an internal program”
  • http://localhost:8081/actuator/heapdump: a management endpoint on the same host

The server sits inside the internal network. Anywhere it can reach, the attacker can reach through it. The defense needs several layers:

  1. Restrict the URL’s form: allow only https, the default port, and URLs without a username or password
  2. Resolve the URL and check every IP: reject loopback, private ranges, link-local (including 169.254.169.254), CGNAT, IPv6 unique local, and similar addresses
  3. Do not follow redirects: an attacker can make a legitimate external URL respond with a 302 that redirects to an internal address
  4. Handle DNS rebinding: the attacker’s domain resolves to an external IP the first time and passes the check, then resolves to an internal IP when the actual connection is made. Use the result of the same resolution for both the check and the connection, or leave it to the next layer
  5. Protect at the network level: send all such outbound requests through an egress proxy that can reach only the internet, or use network policies to stop the service that sends webhooks from reaching internal ranges. This is the most reliable layer, because it does not depend on every check in the application being written correctly
  6. Limit resources: short timeouts, a response size limit, and a per-speaker call rate limit (Timeouts, Retries, Backoff, and Jitter)

Comparing options

Option Good for Cost
RBAC embedded in code, plus owner conditions Most CRUD services Rules are scattered across services; you need tests to make sure every endpoint has a check
A centralized policy engine (OPA, Cedar) Several services must share consistent rules, and policies need central auditing and review The data a decision needs has to be sent to the policy engine; one more component to operate and one more hop of latency
A ReBAC system (OpenFGA, SpiceDB) Products with complex sharing, hierarchy, and delegation (document collaboration, organizations and teams) Relationship data must stay in sync with business data; list queries need their own design
Database row-level security Multi-tenant isolation, as a second line of defense outside the application Depends on the database (PostgreSQL supports it, MySQL has no native mechanism); the connection pool must set the right tenant on every connection

The talk platform’s choice: Spring Security roles and scopes for the function level. For the object level, owner and tenant conditions go into every query, and speakers’ permissions on talks go through one centralized check component. No ReBAC system for now; re-evaluate when requirements such as “co-managing a talk” or “department permissions within a company” appear.

In Java

1. Deny by default; rules and annotations for the function level

java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class ApiSecurityConfig {

    @Bean
    SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/actuator/health/**").permitAll()
                        .requestMatchers("/admin/**").hasRole("PLATFORM_ADMIN")
                        .requestMatchers("/v1/**").authenticated()
                        .anyRequest().denyAll())                 // any path not listed is denied
                .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
        return http.build();
    }
}
  • anyRequest().denyAll(): if you forget to add a rule for a new endpoint, the result is “nobody can access it” rather than “anyone can access it”
  • The roles in the JWT have to be mapped to authorities that start with ROLE_, configured through JwtAuthenticationConverter; that part is omitted here

2. Object level: the owner condition goes in the query

java
/** The current member, taken from the verified JWT. member_id is a custom claim the IdP adds to the access token. */
public record CurrentMember(long memberId, String tenantId) {

    public static CurrentMember from(Jwt jwt) {
        return new CurrentMember(((Number) jwt.getClaim("member_id")).longValue(), jwt.getClaimAsString("tenant_id"));
    }
}

public interface RegistrationRepository extends Repository<Registration, Long> {

    Optional<Registration> findByIdAndMemberId(long id, long memberId);
}

@RestController
@RequestMapping("/v1/registrations")
public class RegistrationController {

    private final RegistrationRepository registrations;

    public RegistrationController(RegistrationRepository registrations) {
        this.registrations = registrations;
    }

    @GetMapping("/{id}")
    public RegistrationView get(@PathVariable long id, @AuthenticationPrincipal Jwt jwt) {
        CurrentMember me = CurrentMember.from(jwt);
        return registrations.findByIdAndMemberId(id, me.memberId())
                .map(RegistrationView::from)
                // "does not exist" and "not yours" get exactly the same response
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
    }
}

Speakers’ permissions on talks live in one component that can be tested on its own:

java
@Component("lectureAuthz")
public class LectureAuthorization {

    private final JdbcClient jdbc;

    public LectureAuthorization(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    public boolean isSpeakerOf(long lectureId, Authentication authentication) {
        if (!(authentication.getPrincipal() instanceof Jwt jwt)) {
            return false;
        }
        long memberId = CurrentMember.from(jwt).memberId();
        return jdbc.sql("SELECT COUNT(*) FROM lecture WHERE id = :id AND speaker_member_id = :memberId")
                .param("id", lectureId)
                .param("memberId", memberId)
                .query(Long.class)
                .single() > 0;
    }
}

@Service
public class AttendeeService {

    private final AttendeeRepository attendeeRepository;

    public AttendeeService(AttendeeRepository attendeeRepository) {
        this.attendeeRepository = attendeeRepository;
    }

    @PreAuthorize("@lectureAuthz.isSpeakerOf(#lectureId, authentication)")
    public List<AttendeeView> attendeesOf(long lectureId) {
        // Property level: the speaker version of the response has only the name and a masked email
        return attendeeRepository.findConfirmedByLectureId(lectureId).stream()
                .map(AttendeeView::forSpeaker)
                .toList();
    }
}
  • The permission check goes in the service, not the controller: when the same method is called from gRPC, a message consumer, or a scheduled job, the check still runs
  • #lectureId relies on parameter names being kept at compile time (-parameters), which the Spring Boot build plugins add by default
  • Here the check and the read are two queries. If the talk is transferred to another speaker between the two, there can be a brief inconsistency; for data like talks, which rarely change hands, that is acceptable

3. Property level: explicit types for both input and output

java
/** Members can change only these two fields; role and status are not here, so they cannot be written. */
public record UpdateProfileRequest(
        @NotBlank @Size(max = 50) String displayName,
        @Pattern(regexp = "^09\\d{8}$") String mobile) {
}

public record AttendeeView(String displayName, String maskedEmail) {

    static AttendeeView forSpeaker(Attendee attendee) {
        return new AttendeeView(attendee.displayName(), mask(attendee.email()));
    }

    private static String mask(String email) {
        int at = email.indexOf('@');
        return at <= 1 ? "***" + email.substring(Math.max(at, 0)) : email.charAt(0) + "***" + email.substring(at);
    }
}

4. SSRF: checking the webhook URL

java
@Component
public class WebhookTargetValidator {

    public URI validate(String raw) {
        URI uri = URI.create(raw);
        if (!"https".equals(uri.getScheme()) || uri.getHost() == null || uri.getRawUserInfo() != null
                || (uri.getPort() != -1 && uri.getPort() != 443)) {
            throw new InvalidWebhookException("Only https URLs on the default port are allowed");
        }
        try {
            for (InetAddress address : InetAddress.getAllByName(uri.getHost())) {
                if (isInternal(address)) {
                    throw new InvalidWebhookException("The URL must not point to an internal address");
                }
            }
        } catch (UnknownHostException e) {
            throw new InvalidWebhookException("Cannot resolve the URL");
        }
        return uri;
    }

    private static boolean isInternal(InetAddress address) {
        if (address.isAnyLocalAddress() || address.isLoopbackAddress() || address.isLinkLocalAddress()
                || address.isSiteLocalAddress() || address.isMulticastAddress()) {
            return true;                                   // covers 10/8, 172.16/12, 192.168/16, 169.254/16, and more
        }
        byte[] ip = address.getAddress();
        if (ip.length == 4) {
            return (ip[0] & 0xFF) == 100 && (ip[1] & 0xC0) == 64;   // 100.64.0.0/10 (CGNAT)
        }
        return (ip[0] & 0xFE) == 0xFC;                     // fc00::/7 (IPv6 unique local)
    }
}
  • This check is the first layer, not the whole defense: it cannot stop DNS rebinding (after the check and before the connection, the domain is changed to resolve to an internal address). The request that actually sends the webhook has to go through an egress proxy that can reach only the internet, or the network layer has to block this service from reaching internal ranges
  • The JDK’s HttpClient does not follow redirects by default (Redirect.NEVER); do not change that for convenience
  • Check when the URL is stored and again before every send, because what a domain resolves to can change

The code above is written from the official Spring Boot 4.1 and Spring Security 7.1 documentation; it has not been compiled or run.

Pitfalls and gotchas

  • Hiding it only in the frontend: the button is gone, but the API is still there
  • Authorization written in the controller: a new gRPC interface, message consumer, or batch job calls the same service, and nothing is checked
  • Batch and nested requests checked only at the first level: GraphQL nested fields and every ID in a batch API each need their own check (REST, gRPC, and GraphQL)
  • New endpoints without rules: the default is authenticated(), so anyone who is logged in can call admin functions. The default should be deny
  • PATCH merged into the entity: if you merge the request JSON into the entity and save it, an attacker can change the owner field along the way
  • Role explosion: every new requirement adds a role, until nobody knows who has which permissions. When you see this sign, the rules are really attributes or relationships, and it is time to switch models
  • Admin impersonation without records: support “logs in as the user” to investigate an issue, and every action looks as if the user did it. Impersonation needs its own identity marker and audit log
  • Authorization tests that only test “allowed”: every endpoint needs test cases for “someone else’s data”, “no role”, and “another tenant”, confirming that the response is 404 or 403

Attack scenarios

Attack How it happens Defense
Enumerating IDs (BOLA) Trying sign-up, order, and file IDs in sequence Owner condition in the query; always 404 when nothing is found; monitor the 404 rate per account
Parameters overriding identity The request carries memberId or tenantId, and the server uses it as a query condition Take identity and tenant only from the verified token
Mass assignment Sending extra role, status, or price fields Each operation has its own request type
Calling hidden admin APIs Finding admin endpoint paths in the frontend JavaScript Function-level authorization; deploy the admin interface separately from the regular API, or on a separate domain
Bypassing the new version’s checks Calling an old API version that is still online, or internal debug endpoints An API inventory; retire old versions; do not expose internal endpoints
Reading data through a side door Search result snippets, export files, reports, autocomplete, total counts Apply the same condition to every read path
Cross-tenant access Company A’s admin changes the company code in the URL to company B’s Tenant condition from the token; where feasible, add database-level isolation as a second line of defense
SSRF A webhook, import URL, or image URL pointing at the metadata service or an internal service URL checks, no following redirects, egress proxy, IMDSv2
Still acting after permission is revoked A speaker who was removed can still download the list until the token expires High-risk operations look up current permissions; short-lived tokens

When to use it, and when not to

  • Always: every API needs all three levels of authorization; this is not a design option you can trade away
  • Use RBAC: for the function level, and wherever permissions depend only on job function
  • Use owner conditions: for most object-level needs; simple, fast, and easy to test
  • Use ABAC or a policy engine: when rules combine attributes (tenant, region, time, data classification), or several services need consistent, auditable policies
  • Use ReBAC: when sharing, delegation, or multi-level organizations appear in the requirements, and “who can see this record” has to be answerable in reverse
  • Do not adopt too early: in a system where the only rule is “only you can see your own data”, a Zanzibar-style system just adds another copy of data to keep in sync and another service to operate

References

Comments