Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsSpring Boot In Depth & Scenarios
✓ FreeIntermediate· 10 min read

Spring Boot Security Scenarios — Interview Questions

Securing Actuator, protecting sensitive data across roles, authentication vs authorization, Spring Security 6 setup, securing microservices with OAuth2/JWT, configuring against common threats, JWT done safely, form login, rate limiting with Bucket4j, CORS, and WebSocket security.

Published September 25, 2026


How to use this lesson

Security answers must use current APIs. Spring Boot 3 ships Spring Security 6, where WebSecurityConfigurerAdapter and authorizeRequests() are gone. Show the SecurityFilterChain bean style, and pair each mechanism with the threat it stops.

Q1. How do you secure the Actuator endpoints?

Short answer:

  1. Expose only what you need. Only health is exposed over HTTP by default. Add endpoints deliberately (management.endpoints.web.exposure.include=health,info,prometheus).
  2. Require authentication and an operations role for everything except health and readiness.
  3. Isolate the endpoints: a separate management.server.port, bound to an internal network or blocked at the ingress.
  4. Limit the details: management.endpoint.health.show-details=when-authorized, and keep the default secret masking.
  5. Never expose heapdump or env publicly, because they leak secrets.
@Bean
@Order(1)
SecurityFilterChain actuatorSecurity(HttpSecurity http) throws Exception {
    return http.securityMatcher(EndpointRequest.toAnyEndpoint())
            .authorizeHttpRequests(a -> a
                .requestMatchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)).permitAll()
                .anyRequest().hasRole("OPS"))
            .httpBasic(Customizer.withDefaults())
            .build();
}

Learn it in depth → Health Checks

Q2. How would you secure sensitive data accessed by users with different roles?

Short answer: Layer the defences:

  • Strong authentication: OIDC/SSO, MFA for privileged roles.
  • Authorisation at URL and method level: @PreAuthorize, including ownership checks ("users can read only their own records"), not just roles.
  • Data minimisation: DTOs per role, and field masking (showing the last 4 digits).
  • Encryption in transit (TLS) and at rest: database or disk encryption, plus column-level encryption for highly sensitive fields.
  • Secrets in a vault.
  • Audit logs of who accessed or changed sensitive data.
  • Least privilege for database users and services.
@PreAuthorize("hasRole('SUPPORT') or #customerId == authentication.principal.customerId")
public CustomerProfile profile(long customerId) { … }

Q3. Sensitive data with multiple roles: what about the database and logs? (The same scenario, with a follow-up)

Short answer:

  • Database: encrypt sensitive columns (with JPA AttributeConverters and keys held in a KMS), and use row-level security or tenant filters where appropriate. Give the application a least-privilege DB user.
  • Logs: mask PII and secrets in logging (Logback masking patterns), and never log tokens or card data.
  • Exports: apply the same authorisation rules to reports and exports. They're a common data-leak path.

Learn it in depth → Payment Security

Q4. What's the difference between authentication and authorization in Spring Security?

Short answer: Authentication establishes who the caller is (a password, token or certificate). It produces an Authentication in the SecurityContext. Authorization decides what that caller may do, based on their granted authorities, and on rules evaluated by the AuthorizationManager at URL, method or domain-object level.

Key points to cover:

  • A 401 means "not authenticated". A 403 means "authenticated, but not allowed".

Learn it in depth → Authentication Mechanics

Q5. How is Spring Security implemented in a Spring Boot application?

Short answer:

  1. Add spring-boot-starter-security. Every endpoint is secured by default, with a generated password.
  2. Declare a SecurityFilterChain bean that sets the URL rules and the authentication mechanism.
  3. Provide users through a UserDetailsService (a database) or an external identity provider (OAuth2/OIDC).
  4. Use a PasswordEncoder (BCrypt or Argon2, through DelegatingPasswordEncoder).
  5. Enable method security with @EnableMethodSecurity.
@Configuration
@EnableMethodSecurity
class SecurityConfig {
    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(a -> a
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .build();
    }
    @Bean PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); }
}

Common trap: describing extends WebSecurityConfigurerAdapter and configure(HttpSecurity). It was removed in Spring Security 6.

Learn it in depth → Spring Security Overview

Q6. How would you secure a microservices architecture with Spring Boot and Spring Security?

Short answer:

  • A central identity provider (Keycloak, Okta, Auth0, Cognito) issues OAuth2/OIDC tokens.
  • The API gateway validates tokens at the edge, and applies rate limits.
  • Every service is itself an OAuth2 resource server. It validates the JWT's signature and claims (with JWKS key rotation), and enforces its own fine-grained authorisation.
  • Service-to-service calls use the client-credentials grant, or token exchange, plus mTLS (often through a service mesh).
  • Secrets are kept in a vault, and there's centralised audit logging.

Common trap: a single custom "auth service" that hand-rolls JWT signing. Use a standards-based identity provider.

Learn it in depth → Spring OAuth2 Basics

Q7. How do you configure Spring Security against common security concerns?

Short answer: Map each threat to a control:

ThreatControl
Credential stuffing, brute forceRate limiting on login, account lockout or backoff, MFA
Weak password storageBCrypt or Argon2 via DelegatingPasswordEncoder
CSRF (cookie sessions)Spring's CSRF protection, on by default (disable only for stateless token APIs)
Session fixation / hijackingSession-ID rotation on login (the default), HttpOnly/Secure/SameSite cookies, timeouts
XSS, clickjackingSecurity headers: Content-Security-Policy, X-Frame-Options, HSTS (http.headers(...))
Broken access controlDeny by default (anyRequest().authenticated()), method-level checks, ownership checks
Sensitive data exposureTLS, masking, no stack traces in responses

Q8. How would you secure a Spring Boot app with JWT?

Short answer: Let an identity provider issue the tokens, and configure the app as an OAuth2 resource server. Spring validates the signature (fetching keys from the issuer's JWKS endpoint), expiry, issuer and audience on every request, and maps scopes or roles to authorities. The service stays stateless.

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://auth.example.com/realms/shop     # discovery + JWKS
          audiences: orders-api

Key points to cover:

  • Short-lived access tokens (minutes), with refresh tokens handled by the client and identity provider.
  • Revocation is hard with pure JWTs, which is why lifetimes stay short. Use introspection or a denylist for high-risk actions.
  • Don't store JWTs in localStorage in browser apps, because of XSS exposure. Prefer the backend-for-frontend pattern with HttpOnly session cookies.
  • Never accept alg: none, and pin the expected algorithms.

Learn it in depth → Spring JWT Authentication

Q9. Configure basic form-based authentication so that only logged-in users reach certain endpoints.

Short answer (Spring Security 6):

@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(a -> a
            .requestMatchers("/", "/login", "/css/**").permitAll()
            .requestMatchers("/account/**").authenticated()
            .anyRequest().authenticated())
        .formLogin(f -> f.loginPage("/login").defaultSuccessUrl("/account", true))
        .logout(l -> l.logoutSuccessUrl("/"))
        .build();
}

@Bean
UserDetailsService users(UserRepository repo) {                        // load users from the database
    return username -> repo.findByEmail(username)
            .map(u -> User.withUsername(u.getEmail()).password(u.getPasswordHash()).roles(u.getRole()).build())
            .orElseThrow(() -> new UsernameNotFoundException(username));
}

Common trap: configure(AuthenticationManagerBuilder auth) and http.authorizeRequests(). Those are the removed Spring Security 5 API.

Q10. How would you implement rate limiting on API endpoints?

Short answer:

  • At the edge: Spring Cloud Gateway's RequestRateLimiter (a Redis token bucket), NGINX/Envoy, or an API gateway service.
  • In the application: Bucket4j (a token bucket) in a filter or interceptor. Key it by API key, user or IP. Store the buckets in Redis (or Hazelcast), so the limits hold across instances. Return 429 Too Many Requests with a Retry-After header.
@Component
class RateLimitFilter extends OncePerRequestFilter {
    private final ProxyManager<String> buckets;                         // Bucket4j + Redis
    private final Supplier<BucketConfiguration> config = () -> BucketConfiguration.builder()
            .addLimit(Bandwidth.builder().capacity(100).refillGreedy(100, Duration.ofMinutes(1)).build())
            .build();

    @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        String key = "rl:" + apiKeyOf(req);
        if (buckets.builder().build(key, config).tryConsume(1)) {
            chain.doFilter(req, res);
        } else {
            res.setStatus(429);
            res.setHeader("Retry-After", "60");
        }
    }
}

Learn it in depth → Design a Rate Limiter

Q11. Your backend must accept cross-origin requests from one specific frontend domain. How do you configure CORS?

Short answer: Allow exactly that origin, the methods and headers it needs, and credentials only if required. Configure it globally, and make sure Spring Security applies it too. Otherwise, preflight OPTIONS requests are rejected before MVC ever sees them.

@Bean
CorsConfigurationSource corsConfigurationSource() {
    var cfg = new CorsConfiguration();
    cfg.setAllowedOrigins(List.of("https://shop.example.com"));
    cfg.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    cfg.setAllowedHeaders(List.of("Authorization", "Content-Type"));
    cfg.setAllowCredentials(true);
    cfg.setMaxAge(Duration.ofHours(1));
    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", cfg);
    return source;
}
// and in the SecurityFilterChain: http.cors(Customizer.withDefaults())

Key points to cover:

  • @CrossOrigin on controllers works for small cases.
  • Never combine allowCredentials(true) with a wildcard origin (Spring rejects it). CORS is a browser protection, not a server-side access control.

Q12. Securing sensitive data for different roles: what would you audit and monitor? (Another variant of the question)

Short answer:

  • Audit every read and change of sensitive records (who, what, when, from where), in append-only storage.
  • Alert on anomalies: bulk exports, access outside business hours, repeated 403s.
  • Review role assignments periodically, and remove unused privileges.
  • Monitor authentication events. Spring Security publishes AuthenticationSuccessEvent and AbstractAuthenticationFailureEvent for you to record.

Q13. What security challenges are specific to WebSockets in Spring Boot?

Short answer:

  • Authentication happens only at the handshake. Long-lived connections outlive the token, so re-validate, or drop connections when the token expires.
  • Cross-Site WebSocket Hijacking. Browsers send cookies with the handshake, so check the Origin header (setAllowedOrigins).
  • Authorisation must be per message and per destination. With STOMP, secure SUBSCRIBE and SEND destinations (Spring Security's message authorisation), not just the connection.
  • Validation and rate limiting of incoming messages, to stop floods and oversized payloads.
  • Encryption: use wss:// only.
  • Resource exhaustion from many idle connections.
@Bean
AuthorizationManager<Message<?>> messageAuthorization(MessageMatcherDelegatingAuthorizationManager.Builder m) {
    return m.simpDestMatchers("/app/admin/**").hasRole("ADMIN")
            .simpSubscribeDestMatchers("/user/queue/**").authenticated()
            .anyMessage().denyAll()
            .build();
}

Follow-up questions this topic invites — and their answers

Q: Why is CSRF protection usually disabled for REST APIs? A: CSRF exploits the browser automatically attaching cookies. APIs authenticated with a bearer token in the Authorization header aren't vulnerable. Keep CSRF enabled for any cookie-based session authentication, including BFFs.

Q: hasRole('ADMIN') vs hasAuthority('ROLE_ADMIN')? A: They're equivalent. hasRole adds the ROLE_ prefix automatically. Scopes from JWTs map to authorities such as SCOPE_orders.read, which you check with hasAuthority.

Q: How do you test security rules? A: With spring-security-test: @WithMockUser, or jwt() request post-processors in MockMvc. Assert 401 for anonymous callers, 403 for wrong roles, and 200 for the right ones.

Q: How do you rotate JWT signing keys without downtime? A: Publish the new key in the JWKS alongside the old one, start signing with the new key, and remove the old key after the longest token lifetime has passed. Resource servers pick up keys by kid automatically.

Previous

Spring Boot Async, Events & Messaging — Interview Questions

Next

Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions

AI Tutor

Lesson: Spring Boot Security Scenarios — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.