Lesson 8 of 12 · 12 min · Building REST APIs

Spring Security basics: authentication, authorization and JWT

Covers: Spring Boot 4.1 with Spring Security 7 on Java 17 or newer. Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • The difference between authentication and authorization
  • What Spring Security does the moment you add it
  • Configure a SecurityFilterChain with authorizeHttpRequests
  • Store passwords safely with a PasswordEncoder
  • Protect methods with roles, and secure a stateless API with JWT, CORS and CSRF decisions

In simple words

Security answers two questions. Authentication: "Who are you?" (log in with a password). Authorization: "Are you allowed to do this?" (an ordinary user cannot delete other people's orders). Spring Security sits in front of your application like a security guard at a building gate: every request passes through it first, and it decides whether to let the request in, ask for credentials, or turn it away.

Words to know

  • Authentication: proving who you are.
  • Authorization: deciding what an authenticated user may do.
  • Filter chain: the ordered list of security checks each request passes through.
  • JWT (JSON Web Token): a signed token that carries the user's identity and claims.

What happens when you add it

Adding spring-boot-starter-security secures every endpoint immediately: all requests need a login (HTTP Basic and a form login), CSRF protection is on, and Boot generates a user called user with a random password printed in the log at startup. That is a safe default. You then customise it with a SecurityFilterChain bean. (The old WebSecurityConfigurerAdapter was removed; configuration is by beans and lambda DSL.)

A first configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health", "/api/auth/**").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())            // everything else needs a login
            .httpBasic(Customizer.withDefaults())         // simple option for APIs and tests
            .csrf(csrf -> csrf.disable())                 // only for stateless token APIs, see below
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();   // bcrypt by default
    }
}

Rules are evaluated in order; the first match wins, so put specific rules first and anyRequest() last. A safe stance is deny by default: anyRequest().authenticated() (or denyAll()), then open only what must be public. hasRole("ADMIN") checks the authority ROLE_ADMIN (the ROLE_ prefix is added for you); hasAuthority("order:write") checks the exact string.

Users and passwords

Spring Security needs a UserDetailsService to load a user by name. For learning, an in-memory one:

@Bean
UserDetailsService users(PasswordEncoder encoder) {
    return new InMemoryUserDetailsManager(
        User.withUsername("asha").password(encoder.encode("s3cret!")).roles("USER").build(),
        User.withUsername("admin").password(encoder.encode("adm1n!")).roles("ADMIN", "USER").build());
}

In real systems, implement UserDetailsService to load from your users table (a JPA repository), or delegate login to an identity provider (Keycloak, Auth0, Google) with OAuth 2.0 / OpenID Connect.

Passwords: never store plain text, and never use fast hashes (MD5, SHA-1, plain SHA-256). Use a slow, salted, adaptive algorithm: bcrypt, Argon2 or scrypt/PBKDF2. PasswordEncoderFactories.createDelegatingPasswordEncoder() stores hashes with an id prefix ({bcrypt}$2a$10$...), so you can upgrade algorithms later. Never log passwords or return them in JSON (a DTO has no password field; this is another reason for DTOs). Enforce reasonable length rules, and consider checking against breached-password lists.

Authorization at the method level

URL rules are coarse. Fine-grained rules belong on service methods:

@Configuration
@EnableMethodSecurity                       // turns on @PreAuthorize and @PostAuthorize
class MethodSecurityConfig {}

@Service
class OrderService {

    @PreAuthorize("hasRole('ADMIN')")
    public void deleteOrder(long id) { ... }

    @PreAuthorize("#customerId == authentication.principal.id or hasRole('ADMIN')")
    public List<OrderResponse> ordersOf(long customerId) { ... }

    @PostAuthorize("returnObject.owner == authentication.name")
    public OrderResponse get(long id) { ... }
}

The most important authorization rule is object-level: when a user asks for /orders/5, check that order 5 belongs to them. Missing this check is the top web API vulnerability (Broken Object Level Authorization, OWASP API Security Top 10; also called IDOR). Authentication alone is not enough.

Stateless APIs and JWT

A browser app with server sessions uses cookies and CSRF protection. A mobile app or single-page app talking to an API usually sends a token in the Authorization: Bearer <token> header on every request, and the server keeps no session.

A JWT is three Base64URL parts, header.payload.signature. The payload holds claims (sub the user id, exp expiry, roles). The server verifies the signature with a key, so it trusts the claims without a database lookup. The payload is encoded, not encrypted: anyone can read it, so never put secrets in a JWT.

With the OAuth 2.0 resource server support, Spring validates tokens issued by an identity provider:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security-oauth2-resource-server</artifactId>
</dependency>
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.example.com/realms/shop
http
    .authorizeHttpRequests(a -> a.anyRequest().authenticated())
    .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
    .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

Spring fetches the issuer's public keys, validates the signature, expiry and issuer, and builds an Authentication from the claims (map the roles claim to authorities with a JwtAuthenticationConverter). Using a standard identity provider is safer than writing your own login endpoint that mints tokens. If you do issue tokens yourself: use a strong signing key kept out of the code, short expiry (minutes) with refresh tokens, validate exp, iss and aud, reject the none algorithm, and plan for revocation (a deny list, or short lifetimes).

Where to keep a token on a web client: an HttpOnly, Secure, SameSite cookie resists theft by JavaScript (XSS) but needs CSRF thought; localStorage is readable by any injected script. There is no perfect answer; avoid XSS first.

CSRF and CORS

  • CSRF (cross-site request forgery) tricks a logged-in browser into sending a request the user did not intend, and works because the browser attaches cookies automatically. Keep CSRF protection on for apps that use cookie sessions. You may disable it for APIs that authenticate only with an Authorization header token, because browsers do not attach that header on their own.
  • CORS (cross-origin resource sharing) is the browser rule that blocks a page on https://app.example.com from calling https://api.example.com unless the API allows it. It is not a security feature of the server (curl ignores it). Configure allowed origins explicitly:
@Bean
CorsConfigurationSource cors() {
    var config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://app.example.com"));     // never "*" with credentials
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return source;
}
// then: http.cors(Customizer.withDefaults())

Other protections

Spring Security adds sensible headers by default (X-Content-Type-Options, cache control, frame options). Add HTTPS everywhere (terminate TLS at a proxy or in Boot), rate limiting on login endpoints (at the gateway or with a library such as Bucket4j), account lockout or delays after repeated failures, audit logging of logins and permission failures, and keep dependencies updated (security advisories for Spring, Jackson and Tomcat are frequent).

Return 401 for not authenticated and 403 for not allowed (configure the AuthenticationEntryPoint and AccessDeniedHandler to write ProblemDetail-style JSON). Do not reveal whether a username exists ("invalid username or password", the same message for both).

Testing

With spring-boot-starter-security-test:

@WebMvcTest(AdminController.class)
class AdminControllerSecurityTests {
    @Autowired MockMvcTester mvc;

    @Test
    void anonymousGets401() {
        assertThat(mvc.get().uri("/api/admin/stats")).hasStatus(HttpStatus.UNAUTHORIZED);
    }

    @Test
    @WithMockUser(roles = "USER")
    void plainUserGets403() {
        assertThat(mvc.get().uri("/api/admin/stats")).hasStatus(HttpStatus.FORBIDDEN);
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void adminGets200() {
        assertThat(mvc.get().uri("/api/admin/stats")).hasStatusOk();
    }
}

Boot 4 needs the separate spring-boot-starter-security-test for @WithMockUser. Write tests for the negative cases: a user must not read another user's data.

Common mistakes

  • Disabling security "temporarily" with permitAll() for everything.
  • Disabling CSRF on cookie-based apps.
  • Plain-text or fast-hash passwords.
  • Putting secrets in a JWT or signing with a weak or committed key.
  • Missing object-level checks (any logged-in user can read any order).
  • allowedOrigins("*") with credentials, or confusing CORS with security.
  • Rolling your own authentication instead of using a proven identity provider.
  • Rules in the wrong order (anyRequest() first).
  • Exposing Actuator endpoints such as env and heapdump.

Try it yourself

  1. Add the security starter, read the generated password in the log, and call an endpoint with curl -u user:<password>.
  2. Configure a SecurityFilterChain with a public GET /api/products, an admin-only /api/admin/** and everything else authenticated.
  3. Add two in-memory users with encoded passwords and write the three security tests above.
  4. Add @PreAuthorize so a user can read only their own orders, and write a test that user A cannot read user B's order.
  5. Start a local identity provider (Keycloak in Docker), point the resource server at it and call the API with a bearer token.

Check yourself

What is the difference between authentication and authorization?

Authentication proves who the caller is; authorization decides what that caller is allowed to do.

Why should passwords be hashed with bcrypt or Argon2, not SHA-256?

They are deliberately slow and salted, which makes brute-forcing stolen hashes impractical; fast hashes can be guessed billions of times a second.

When is it acceptable to disable CSRF protection?

For a stateless API authenticated only by a token in the Authorization header, since browsers do not attach it automatically; keep it enabled for cookie-based sessions.

Is a JWT encrypted?

No, a normal signed JWT is only Base64-encoded; anyone can read the claims, so it must not hold secrets, and the signature must be verified.

Interview questions

How does Spring Security work internally?

Requests pass through a chain of servlet filters (a SecurityFilterChain) that handle authentication (reading credentials or a token, building an Authentication stored in the SecurityContext) and authorization (authorizeHttpRequests and method security), before reaching the controller.

How would you secure a REST API used by a React app?

Use an identity provider with OAuth 2.0/OIDC, have the API act as a JWT resource server, run stateless, configure CORS for the app's origin, enforce HTTPS, add role and object-level authorization, and protect against XSS so tokens are not stolen.

What is IDOR (broken object-level authorization) and how do you prevent it?

Letting a user access another user's object by changing an id in the request. Prevent it by checking ownership or permission for every object access, in the service layer or with @PreAuthorize, and by writing tests for cross-user access.

Summary

  • Adding Spring Security locks everything down; configure a SecurityFilterChain with ordered rules and deny by default.
  • Hash passwords with a delegating encoder (bcrypt); use roles and @PreAuthorize, and always check object ownership.
  • For APIs, use a JWT resource server with a trusted identity provider and stateless sessions; keep CSRF on for cookie sessions; configure CORS explicitly.
  • Test negative cases and never rely on hiding endpoints.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.