Java & Spring
Updated for 2026

Spring Security Core & Config Cheatsheet

Essential configurations, authorization annotations, filter chain setups, JWT integration, and security headers.

Target Version Compatibility

Interactive Skill Mastery

Mark commands as learned to build your customized reference tracker. Retained locally in this browser.

Level:Novice
Command Mastery Progress0 of 17 Mastered (0%)

Filter Chain

SecurityFilterChain filterChain(HttpSecurity http)
IntermediateAdvanced
Define the core security filter chain bean to configure URL authorizations, login, and CSRF options.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

SecurityFilterChain filterChain(HttpSecurity http)

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
AdvancedSecurity
Configure authorization rules requiring authentication for all incoming requests.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
http.headers(headers -> headers.frameOptions(frame -> frame.deny()))
BeginnerBasics
Harden security headers to prevent Clickjacking attacks via X-Frame-Options.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

http.headers(headers -> headers.frameOptions(frame -> frame.deny()))

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
http.exceptionHandling(ex -> ex.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
AdvancedSecurity
Handle authentication entry point errors returning clean HTTP 401 statuses.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

http.exceptionHandling(ex -> ex.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
http.requiresChannel(channel -> channel.anyRequest().requiresSecure())
AdvancedSecurity
Enforce HTTPS channel security for all incoming requests.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

http.requiresChannel(channel -> channel.anyRequest().requiresSecure())

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.

Method Security

@EnableMethodSecurity
AdvancedSecurity
Enable method-level security authorizing access dynamically via expression-based annotations.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

@EnableMethodSecurity

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
@PreAuthorize("hasRole('ADMIN')")
AdvancedSecurity
Restricts method execution to users holding the 'ADMIN' role.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

@PreAuthorize("hasRole('ADMIN')")

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
@PreAuthorize("#id == authentication.principal.id")
AdvancedSecurity
Dynamic method security to verify parameter ID matches current authenticated user ID.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

@PreAuthorize("#id == authentication.principal.id")

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
@PostAuthorize("returnObject.owner == authentication.name")
AdvancedSecurity
Evaluates security rules after method execution, comparing return object details.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

@PostAuthorize("returnObject.owner == authentication.name")

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.

Auth Managers

BCryptPasswordEncoder passwordEncoder()
AdvancedSecurity
Declare a BCrypt password hashing bean for secure password storage and verification.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

BCryptPasswordEncoder passwordEncoder()

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
DaoAuthenticationProvider authProvider()
AdvancedSecurity
Configure a database-backed authentication provider using UserDetailsService.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

DaoAuthenticationProvider authProvider()

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
AuthenticationManager authManager(AuthenticationConfiguration config)
AdvancedSecurity
Configure and obtain the central AuthenticationManager bean for manual user login.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

AuthenticationManager authManager(AuthenticationConfiguration config)

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.

CORS & CSRF

http.csrf(csrf -> csrf.disable())
BeginnerBasics
Disable CSRF protection (common in stateless REST APIs utilizing JWTs).

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

http.csrf(csrf -> csrf.disable())

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
CorsConfigurationSource corsConfigurationSource()
BeginnerBasics
Define CORS origins, headers, and HTTP methods permitted by the application.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

CorsConfigurationSource corsConfigurationSource()

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.

JWT & OAuth2

http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
BeginnerBasics
Configure stateless session creation policy for REST APIs to prevent cookies storage.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
http.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
AdvancedSecurity
Configure the resource server to validate incoming JWTs automatically.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

http.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.
JwtDecoder jwtDecoder()
AdvancedSecurity
Configure the decoder bean to parse, validate signatures, and verify claims of incoming JSON Web Tokens.

When to Use

When configuring authentication, secure endpoints, HTTP filters, or method authorization controls inside Java Spring Boot backend web services.

Common Mistakes

Disabling security rules indiscriminately or failing to authenticate REST APIs using correct filter chain ordering.

Shortcut / Pro-Tip

Annotate controllers using expressions like `@PreAuthorize` to manage precise user roles cleanly.

Example

JwtDecoder jwtDecoder()

Output Example

Console / Terminal
// Fully authorized and processed within Spring Security Context.

Spring Security Best Practices

1Enforce Stateless Sessions for REST APIs

Always configure SessionCreationPolicy.STATELESS when securing REST microservices. Store user contexts inside client-side JWT tokens to completely eliminate server session states.

2Harden Security Headers

Harden headers automatically by utilizing HttpSecurity.headers to enforce Clickjacking defense (frameOptions), Content Security Policy (CSP), and HSTS.

3Secure Methods via Method Security

Enable @EnableMethodSecurity and utilize standard Expression-Based annotations like @PreAuthorize and @PostAuthorize to secure specific service-tier methods dynamically.

4Define Explicit CORS Origins

Configure tight, non-wildcard Allowed Origins, Methods, and Headers on your active CorsConfigurationSource to prevent malicious cross-origin scripts from extracting web data.

5Harness Cryptographically Strong Hashing

Declare a cryptographically strong password hashing bean such as BCryptPasswordEncoder to transparently store and match passwords securely.

Common Spring Security Errors & Solutions

Error

Circular Dependency with PasswordEncoder and WebSecurity

Solution

Isolate your PasswordEncoder bean in a standalone @Configuration class (e.g. SecurityBeansConfig) distinct from your primary HttpSecurity Filter Chain class.

Error

HTTP 403 Forbidden on POST/PUT requests in REST APIs

Solution

Spring Security enables CSRF defense by default, which rejects state-changing requests without CSRF tokens. Disable CSRF for stateless JWT APIs using http.csrf(csrf -> csrf.disable()).

Error

AccessDeniedException when validating custom JWT claims

Solution

Ensure that your custom JWT Filter or AuthenticationEntryPoint returns a serialized JSON payload containing custom error statuses instead of letting the servlet container crash.

Error

Custom filter does not execute in the correct sequence

Solution

Explicitly arrange your filter chain inside the SecurityFilterChain configuration using methods like http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class).

Error

CORS configuration ignored or bypassed by Spring Security

Solution

Make sure you declare http.cors(Customizer.withDefaults()) before calling authorizeHttpRequests, ensuring CORS pre-flight OPTIONS requests are handled ahead of authorization filters.

Common Spring Security Interview Questions

Q1What is the primary architectural concept of Spring Security?

Spring Security is built entirely on a chain of Servlet Filters (the DelegatingFilterProxy and FilterChainProxy) which intercept incoming HTTP requests to handle authentication, authorization, CSRF protection, and security headers before the requests reach the controller layer.

Q2What is the difference between Authentication and Authorization in Spring Security?

Authentication is the process of verifying who the user is (typically managed by UserDetailsService and AuthenticationManager). Authorization is the process of verifying what the authenticated user is allowed to do (typically handled by AccessDecisionManager or AuthorizationManager).

Q3How does SecurityContextHolder store authenticated user details?

By default, SecurityContextHolder utilizes a ThreadLocal variable to bind the current active Authentication object to the running execution thread, making authenticated principal details available across any downstream Java classes in that thread.

Q4What is the role of the UserDetailsService interface?

It is a core functional interface containing a single method: loadUserByUsername(String username). It is called by authentication providers to fetch username, encrypted password, and active granted authorities (roles) from custom databases or directories.

Q5Why is the order of filter chains critical in Spring Security?

Because security checks must occur sequentially. For instance, CORS validation and SSL enforcement must execute before JWT authentication, and JWT parsing must occur before method-level authorization. Wrong ordering can either leak access or block valid users.