Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: A Secure Notes API with Token Auth

Build a notes API step by step: signed tokens, stateless filter, scopes, per-owner access checks and tests. Full Spring Security code is read-only, a runnable Java stand-in shows the logic.

In this project you design a small REST API where users keep private notes. It pulls together much of the course: stateless authentication with signed tokens, a filter that turns a token into an identity, rules by role and scope, and a check that a user can only touch their own notes. Think of it as a blueprint; you can implement it in a Spring Boot project and use the tests at the end to prove it works.

Spring Security cannot run on this site. The real configuration is shown read-only, and a self-contained Java program implements the same flow (HMAC-signed token, filter-like gate, ownership checks) so that you can run and modify the logic.

Requirements

Endpoint Rule
POST /auth/login Public. Returns a signed token for valid credentials
GET /notes Authenticated. Returns only your notes
POST /notes Authenticated with scope notes:write
GET /notes/{id} Owner only; others get 404 (do not reveal that the note exists)
DELETE /notes/{id} Owner, or an ADMIN
GET /admin/stats Role ADMIN only

Design decisions: sessions off (STATELESS), CSRF disabled because no cookie carries the credential (see CSRF protection), tokens expire after 15 minutes, passwords stored with a delegating encoder.

Request path

Request Authorization: Bearer ...
Token filter Verify signature and expiry
Rules Role, scope, owner
Controller Runs only if allowed

Each step can stop the request

1 / 2

Step 1: the security configuration (read-only)

With a JWT resource server the filter is provided by Spring; you declare the decoder and the rules:

Java
@Configuration
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/auth/login").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers(HttpMethod.POST, "/notes").hasAuthority("SCOPE_notes:write")
                .anyRequest().authenticated())
            .oauth2ResourceServer(rs -> rs.jwt(Customizer.withDefaults()));
        return http.build();
    }

    @Bean
    JwtDecoder jwtDecoder(@Value("${app.jwt.secret}") String secret) {
        SecretKey key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        return NimbusJwtDecoder.withSecretKey(key).build();
    }
}

The ownership rule belongs in the service or controller layer, where the note is loaded:

Java
@PreAuthorize("hasRole('ADMIN') or @notes.isOwner(#id, authentication.name)")
@DeleteMapping("/notes/{id}")
void delete(@PathVariable long id) { notes.delete(id); }

Step 2: the logic in plain Java (stand-in)

The program issues a token with a subject, roles, scopes and expiry, signs it with HMAC-SHA256, and then "handles requests" by verifying the token before applying the rules. It is a teaching model of what Spring's BearerTokenAuthenticationFilter and JwtDecoder do, not a replacement for them: in production use the real classes and a vetted JWT library.

Java Notes API logic: token, rules, ownership (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output as a test report: each line is one row of the security matrix from testing secured endpoints. The 404 for someone else's note is a deliberate choice, and an admin deleting it works.

Step 3: tests you should write

With the real project, spring-security-test gives you the same matrix:

Java
@Test
void anonymousCannotListNotes() throws Exception {
    mvc.perform(get("/notes")).andExpect(status().isUnauthorized());
}

@Test
void readOnlyScopeCannotCreate() throws Exception {
    mvc.perform(post("/notes").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_notes:read")))
            .contentType(MediaType.APPLICATION_JSON).content("{\"text\":\"x\"}"))
        .andExpect(status().isForbidden());
}

@Test
void userCannotReadSomeoneElsesNote() throws Exception {
    mvc.perform(get("/notes/2").with(jwt().jwt(j -> j.subject("ada"))))
        .andExpect(status().isNotFound());
}

Step 4: extend it

  1. Add refresh tokens with rotation (refresh tokens).
  2. Add login throttling (login throttling).
  3. Emit audit events for denied access (audit events).
  4. Switch the decoder to an issuer URI so an external identity provider signs the tokens (resource server).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can CSRF protection be disabled in this stateless API?

    CSRF abuses credentials that browsers attach automatically, such as session cookies. A Bearer header is not attached by the browser on its own.
  2. 2. Why does GET /notes/2 return 404 for a user who does not own it?

    A 403 would confirm the id exists. Returning 404 gives an attacker nothing to enumerate.
  3. 3. Where should the 'owner or admin' rule live?

    URL rules cannot know who owns record 2. Data-dependent rules belong where the data is available.
  4. 4. What must a verifier check on a token besides the signature?

    A valid signature on an expired or wrong-audience token must still be rejected.

Summary

  • A stateless API turns a verified token into an identity, then applies URL, scope, role and ownership rules.
  • Put data-dependent checks in the service or method-security layer.
  • Choose error codes that leak nothing: 401 for no identity, 403 for no permission, 404 to hide records.
  • Test anonymous, wrong-scope, wrong-owner, admin, tampered and expired cases.

Next: Project: a role-based admin console