skip to content

Spring Security

The whole framework: the servlet filter chain, authentication and authorization, method security, OAuth2 and OIDC, CSRF, CORS and session protection, and the reactive variant. Security questions are where interviewers most reliably find gaps between configuration copied and configuration understood.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

explore

questions

186 · 7 sections

What is DelegatingFilterProxy and why does Spring Security need it?

level: juniorimportance: must knowfreq 70%
basics
~20 s

DelegatingFilterProxy is a servlet Filter registered with the container that forwards requests to a Spring-managed filter bean (the security filter chain). It lets Spring beans act as filters even though the container created the proxy.

open as a page

What is the ExceptionTranslationFilter and what job does it do in the Spring Security filter chain?

level: juniorimportance: must knowfreq 55%
basics
~20 s

It's a filter that catches two security exceptions thrown further down the chain — AuthenticationException (not logged in) and AccessDeniedException (logged in but not allowed) — and turns them into an HTTP response instead of an error page.

open as a page

What is FilterChainProxy in Spring Security, and what is its job?

level: juniorimportance: must knowfreq 60%
basics
~10 s

FilterChainProxy is the single servlet filter Spring Security registers. For each request it picks the first matching SecurityFilterChain and runs that chain's security filters in order.

open as a page

What is the Spring Security filter chain, and why does the ORDER of filters in it matter?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Spring Security is a chain of servlet filters run in a fixed order. Each filter does one job (load context, check CSRF, authenticate, authorize). Order matters because later filters depend on what earlier ones set up — e.g. you must load the user before checking permissions.

open as a page

What is a SecurityFilterChain @Bean and how do you declare one in modern Spring Security?

level: juniorimportance: must knowfreq 80%
basics
~10 s

You write a method annotated with @Bean that takes an HttpSecurity object, configures the rules on it, and returns http.build(), which produces a SecurityFilterChain. Spring registers it to secure your HTTP requests.

open as a page

What does formLogin() enable in Spring Security, and what is the role of UsernamePasswordAuthenticationFilter?

level: juniorimportance: must knowfreq 80%
basics
~10 s

formLogin() turns on a browser login form. Spring adds UsernamePasswordAuthenticationFilter, which intercepts the POST to /login, reads the username and password fields, and asks the AuthenticationManager to verify them.

open as a page

What does Spring Security's logout() DSL configure, and what happens when a user hits /logout?

level: juniorimportance: must knowfreq 58%
basics
~10 s

The logout() DSL wires up a LogoutFilter. When a user POSTs to /logout, the filter clears the logged-in user from the SecurityContext, invalidates the HTTP session, and redirects to a success page (default /login?logout).

open as a page

What is the contract of AuthenticationManager.authenticate()? What are its three possible outcomes?

level: juniorimportance: must knowfreq 70%
basics
~10 s

AuthenticationManager has one method, authenticate(Authentication). It returns a fully authenticated Authentication if credentials are valid, throws an AuthenticationException if they are invalid, or returns null if it cannot decide.

open as a page

What is Spring Security's PasswordEncoder and why should you use it instead of storing passwords directly?

level: juniorimportance: must knowfreq 80%
basics
~20 s

PasswordEncoder is an interface that turns a raw password into a one-way, salted hash. You store the hash, never the plaintext, so a database leak doesn't expose real passwords. Its matches() method verifies a login attempt.

open as a page

What is UserDetailsService in Spring Security, and what does loadUserByUsername return?

level: juniorimportance: must knowfreq 80%
basics
~20 s

UserDetailsService is an interface with one method, loadUserByUsername(String), that looks up a user by name and returns a UserDetails object holding the username, encoded password, and authorities (roles). It throws UsernameNotFoundException if no user exists.

open as a page

What is Spring Security's AccessDeniedHandler and when does it run?

level: juniorimportance: must knowfreq 45%
basics
~10 s

It's the component that produces the HTTP 403 (Forbidden) response when a logged-in user tries to access something they're not allowed to. It runs after an AccessDeniedException is thrown.

open as a page

What is the AuthorizationManager interface in Spring Security, and what did it replace?

level: juniorimportance: must knowfreq 70%
basics
~10 s

AuthorizationManager is Spring Security's interface that decides whether an authenticated user is allowed to access something. In Spring Security 6 it replaced the older AccessDecisionManager and voter system.

open as a page

What is the authorizeHttpRequests DSL in Spring Security, and how do you use requestMatchers with permitAll and authenticated?

level: juniorimportance: must knowfreq 85%
basics
~10 s

authorizeHttpRequests is where you declare which URLs need authorization. You list rules with requestMatchers(path) and choose an access rule like permitAll() (open to everyone) or authenticated() (must be logged in).

open as a page

What is the difference between hasRole and hasAuthority in Spring Security, and how does the ROLE_ prefix affect them?

level: juniorimportance: must knowfreq 82%
basics
~10 s

hasRole('ADMIN') automatically checks for the authority 'ROLE_ADMIN' by adding the ROLE_ prefix. hasAuthority('ROLE_ADMIN') checks the exact string you pass, with no prefix added. They match the same authority only if you include ROLE_ yourself.

open as a page

How do you make a Spring Security REST API return a custom JSON body on a 403 instead of the default blank page?

level: middleimportance: must knowfreq 40%
basics
~10 s

Implement AccessDeniedHandler, set the response status to 403, set content type to application/json, and write your JSON body. Register it via http.exceptionHandling(e -> e.accessDeniedHandler(yourHandler)).

open as a page

What does @EnableMethodSecurity do, and what are its prePostEnabled, securedEnabled, and jsr250Enabled flags?

level: juniorimportance: must knowfreq 70%
basics
~10 s

@EnableMethodSecurity turns on security checks on individual methods (not just URLs). prePostEnabled activates @PreAuthorize/@PostAuthorize (on by default), securedEnabled activates @Secured, and jsr250Enabled activates @RolesAllowed. You put it on a @Configuration class.

open as a page

What do @PreAuthorize and @PostAuthorize do, and how do you turn them on in a Spring application?

level: juniorimportance: must knowfreq 78%
basics
~10 s

@PreAuthorize checks a rule before a method runs; @PostAuthorize checks after it returns. You enable them by adding @EnableMethodSecurity to a configuration class. If the rule is false, access is denied with an exception.

open as a page

What are @Secured and @RolesAllowed in Spring Security, and what do they do?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Both are method-level annotations that restrict who can call a method based on their roles. @RolesAllowed is a Java standard (JSR-250); @Secured is Spring's own. You list allowed roles and Spring blocks everyone else.

open as a page

How do you implement and register a custom PermissionEvaluator in Spring Security 6?

level: middleimportance: must knowfreq 55%
basics
~10 s

Implement the PermissionEvaluator interface (its two hasPermission methods) with your own logic, then publish a MethodSecurityExpressionHandler bean, calling setPermissionEvaluator() so @PreAuthorize's hasPermission() uses it.

open as a page

What variables can you reference in @PreAuthorize/@PostAuthorize SpEL — how do you read method arguments, the principal, and the return value?

level: middleimportance: must knowfreq 72%
basics
~20 s

You can reference method arguments by name (or #p0, #p1), the current user via authentication and principal, and — only in @PostAuthorize — the method's result via returnObject. You combine them with helpers like hasRole() and hasAuthority().

open as a page

What is Spring Authorization Server, and what role do RegisteredClient and RegisteredClientRepository play in it?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Spring Authorization Server is a standalone project that turns your app into an OAuth2/OIDC provider — it issues tokens. A RegisteredClient is one app allowed to request tokens; RegisteredClientRepository stores and looks up those clients.

open as a page

What does JwtTimestampValidator check on an incoming JWT, and why does it allow a small clock skew by default?

level: juniorimportance: must knowfreq 62%
basics
~20 s

JwtTimestampValidator checks the token's time claims: it rejects tokens that are expired (exp) or not yet valid (nbf). It allows a default 60-second clock skew so tokens are not rejected just because server clocks differ slightly.

open as a page

What is an OAuth2AuthorizedClient in Spring Security, and how does oauth2Client() differ from oauth2Login()?

level: juniorimportance: must knowfreq 60%
basics
~20 s

An OAuth2AuthorizedClient holds the access token (and optional refresh token) your app got to call another API on a user's behalf. oauth2Client() lets your app CALL other APIs; oauth2Login() logs the USER into your app.

open as a page

What does oauth2Login() enable in a Spring Security application, and what OAuth2 flow does it use?

level: juniorimportance: must knowfreq 70%
basics
~20 s

oauth2Login() lets users sign in to your app using an external provider like Google or GitHub. It uses the OAuth2 authorization-code flow: Spring redirects the user to the provider, gets a code back, and exchanges it for tokens to log the user in.

open as a page

How do you configure a Spring Security application to act as an OAuth2 Resource Server that accepts JWT bearer tokens?

level: juniorimportance: must knowfreq 78%
basics
~10 s

In the SecurityFilterChain, call http.oauth2ResourceServer(oauth2 -> oauth2.jwt(...)). Add a jwk-set-uri or issuer-uri in application.yml so Spring can fetch the keys and verify each incoming Bearer token's signature.

open as a page

What is CORS, and how do you enable it in a Spring Security application?

level: juniorimportance: must knowfreq 70%
basics
~20 s

CORS lets a browser page from one origin call an API on another origin. In Spring Security you turn it on with http.cors() in the SecurityFilterChain and provide a CorsConfigurationSource bean that lists allowed origins, methods, and headers.

open as a page

What is CSRF, and how does Spring Security protect against it by default?

level: juniorimportance: must knowfreq 72%
basics
~10 s

CSRF tricks a logged-in user's browser into sending an unwanted state-changing request using their cookies. Spring Security defends with a secret token (CsrfFilter) that must accompany every POST/PUT/DELETE/PATCH, which an attacker's site cannot know.

open as a page

Which HTTP security response headers does Spring Security add by default, and where does that behavior come from?

level: juniorimportance: must knowfreq 70%
basics
~10 s

By default Spring Security adds protective response headers automatically: Cache-Control (no-store), X-Content-Type-Options: nosniff, X-Frame-Options: DENY, and Strict-Transport-Security (HSTS) on HTTPS requests. You don't configure anything to get them.

open as a page

What is session fixation and how does Spring Security protect against it by default?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Session fixation is when an attacker forces a victim to use a known session ID, then hijacks it after login. Spring Security defends by changing the session ID at login (changeSessionId), so the old ID is useless.

open as a page

What is the difference between maxSessionsPreventsLogin(true) and (false)?

level: middleimportance: must knowfreq 55%
basics
~20 s

With false (default) a new login is allowed and the oldest session is expired. With true the new login is refused (throws SessionAuthenticationException) and existing sessions stay alive — old sessions win over new ones.

open as a page

In a Spring MockMvc test, how do you make a request run as an authenticated user, and why does a POST often need `.with(csrf())`?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Use SecurityMockMvcRequestPostProcessors: mockMvc.perform(get("/").with(user("alice").roles("ADMIN"))) runs the request as that user. State-changing requests (POST/PUT/DELETE) need .with(csrf()) because CSRF protection rejects them without a valid token.

open as a page

What is ReactiveSecurityContextHolder and how does it differ from the classic SecurityContextHolder?

level: juniorimportance: must knowfreq 58%
basics
~10 s

In WebFlux, ReactiveSecurityContextHolder stores the logged-in user's SecurityContext inside the Reactor Context (attached to the request's reactive stream) instead of a ThreadLocal, so it survives even when work hops between threads.

open as a page

What does @EnableWebFluxSecurity do, and how do you define a security configuration in a Spring WebFlux application?

level: juniorimportance: must knowfreq 70%
basics
~10 s

@EnableWebFluxSecurity turns on Spring Security for a reactive WebFlux app. You then declare a @Bean of type SecurityWebFilterChain that configures which URLs are protected and how users log in.

open as a page

What does @WithMockUser do in a Spring Security test, and what are its defaults?

level: juniorimportance: must knowfreq 78%
basics
~10 s

@WithMockUser runs a test as if a logged-in user made the request, without hitting a real login. By default the user is named 'user' with password 'password' and the role USER.

open as a page

How do you obtain the authenticated user inside a WebFlux controller or service?

level: middleimportance: must knowfreq 60%
basics
~10 s

Either inject the user as a method parameter (@AuthenticationPrincipal MyUser user, or a Mono<Authentication>/Principal argument), or in a service compose ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).

open as a page