Tech Interview RoomStudy guides

Spring Microservices

Secure a microservice with the Spring Security filter chain and JWT. Compare an interceptor, a custom JWT filter and the built-in resource server.

Advanced · 2 min read · Lesson 2 of 5 in Spring Microservices

Problem

Every request to /orders/** must carry a valid JWT; /admin/** requires the ADMIN role; /actuator/health is public. Show where authentication belongs in Spring and how the filter chain works.

How a request flows through Spring Security

Client
Mobile app with Bearer JWT
↓1. HTTP request
Servlet container
DelegatingFilterProxy
↓2. delegates to Spring
Security
FilterChainProxy (picks the matching SecurityFilterChain)
↓3. ordered filters
Filters
CorsFilterBearerTokenAuthenticationFilter or custom JwtAuthFilterExceptionTranslationFilterAuthorizationFilter
↓4. SecurityContext populated, access checked
MVC
DispatcherServletOrderController (@PreAuthorize)

Approach 1: A HandlerInterceptor checking the header (feasible, but the wrong layer)

It runs after the DispatcherServlet, so filters, static resources and error pages are not protected, Spring Security's SecurityContext stays empty (so @PreAuthorize and @AuthenticationPrincipal do not work), and you re-implement 401/403 handling.

java
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String auth = request.getHeader("Authorization");
        if (auth == null || !auth.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;                                         // still no signature check, no roles
        }
        return true;
    }
}

@Configuration
class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/orders/**");
    }
}

Approach 2: A custom OncePerRequestFilter inside the security chain

Validates the token with a JwtDecoder, puts an Authentication into the SecurityContext, and is registered before UsernamePasswordAuthenticationFilter. Correct layer, but you own the parsing, error responses and role mapping. Useful when tokens are non-standard (for example an internal HMAC-signed token).

java
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

class JwtAuthFilter extends OncePerRequestFilter {
    private final JwtDecoder decoder;

    JwtAuthFilter(JwtDecoder decoder) { this.decoder = decoder; }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (header != null && header.startsWith("Bearer ")) {
            try {
                Jwt jwt = decoder.decode(header.substring(7));      // verifies signature, exp, nbf
                List<String> roles = jwt.getClaimAsStringList("roles");
                var authorities = (roles == null ? List.<String>of() : roles).stream()
                    .map(r -> new SimpleGrantedAuthority("ROLE_" + r)).toList();
                SecurityContext context = SecurityContextHolder.createEmptyContext();
                context.setAuthentication(new UsernamePasswordAuthenticationToken(jwt.getSubject(), null, authorities));
                SecurityContextHolder.setContext(context);
            } catch (JwtException e) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
                return;
            }
        }
        chain.doFilter(request, response);                        // anonymous requests are rejected later by AuthorizationFilter
    }
}

@Configuration
class CustomFilterSecurityConfig {
    @Bean
    JwtDecoder hmacJwtDecoder(@Value("${security.jwt.secret}") String secret) {
        return NimbusJwtDecoder.withSecretKey(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")).build();
    }

    @Bean
    SecurityFilterChain customFilterChain(HttpSecurity http, JwtDecoder hmacJwtDecoder) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())                         // stateless bearer-token API
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .addFilterBefore(new JwtAuthFilter(hmacJwtDecoder), UsernamePasswordAuthenticationFilter.class)
            .build();
    }
}

Approach 3: The built-in OAuth2 resource server (optimal for standard JWTs)

Spring validates the token against the issuer's public keys (JWKS), maps claims to authorities with a converter, and returns proper 401/403 responses with WWW-Authenticate headers. Configure spring.security.oauth2.resourceserver.jwt.issuer-uri and almost no code is needed.

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@Configuration
@EnableMethodSecurity
class ResourceServerConfig {
    @Bean
    SecurityFilterChain resourceServerChain(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth -> oauth.jwt(jwt -> jwt.jwtAuthenticationConverter(rolesConverter())))
            .build();
    }

    static JwtAuthenticationConverter rolesConverter() {
        JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter();
        roles.setAuthoritiesClaimName("roles");                   // e.g. Keycloak mapper or custom claim
        roles.setAuthorityPrefix("ROLE_");
        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(roles);
        return converter;
    }
}

@RestController
class SecuredOrderController {
    @GetMapping("/orders/{id}")
    @PreAuthorize("hasRole('USER')")
    String order(@PathVariable String id, @AuthenticationPrincipal Jwt jwt) {
        return "order " + id + " for " + jwt.getSubject();
    }
}

Feasible → optimal

  • Interceptor: works for a demo, but outside Spring Security; unsafe and incomplete.
  • Custom OncePerRequestFilter: correct layer and full control; you maintain token parsing and error handling.
  • Resource server: the standard, least code, correct 401/403 semantics, key rotation via JWKS. Use it unless your token format is non-standard. Test with spring-security-test: mockMvc.perform(get("/orders/1").with(jwt().authorities(new SimpleGrantedAuthority("ROLE_USER")))).

Follow-up questions interviewers ask

Try answering each one before you open it.

Related: how do you add a filter that runs for every request, for example request logging or tenant resolution?

Extend OncePerRequestFilter (guarantees one execution per request, even with forwards) and either add it to the security chain at a precise position (addFilterAfter(filter, BearerTokenAuthenticationFilter.class) when it needs the authenticated user), or register it as a normal servlet filter with @Component plus @Order (or a FilterRegistrationBean with URL patterns) when it does not depend on security.

Related: how do you secure service-to-service calls?

The calling service obtains its own token with the client credentials grant (spring-boot-starter-oauth2-client with an OAuth2AuthorizedClientManager, or an OAuth2ClientHttpRequestInterceptor on RestClient in Spring Security 6.4+), and the receiving service validates it like any JWT and checks scopes such as SCOPE_inventory:read. Add mTLS at the network level (service mesh) for transport identity.

Related: why can CSRF protection be disabled here but not for a browser session app?

CSRF exploits the browser automatically attaching cookies to cross-site requests. A bearer token in the Authorization header is never attached automatically, so stateless token APIs are not vulnerable. If you use cookie-based sessions (a server-side web app or a BFF), keep CSRF protection on.