Spring Security Core & Config Cheatsheet
Essential configurations, authorization annotations, filter chain setups, JWT integration, and security headers.
Interactive Skill Mastery
Mark commands as learned to build your customized reference tracker. Retained locally in this browser.
Filter Chain
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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.Method Security
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
@EnableMethodSecurityOutput Example
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.Auth Managers
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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.CORS & CSRF
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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.JWT & OAuth2
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
// Fully authorized and processed within Spring Security Context.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
// Fully authorized and processed within Spring Security Context.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
// 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
Circular Dependency with PasswordEncoder and WebSecurity
Isolate your PasswordEncoder bean in a standalone @Configuration class (e.g. SecurityBeansConfig) distinct from your primary HttpSecurity Filter Chain class.
HTTP 403 Forbidden on POST/PUT requests in REST APIs
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()).
AccessDeniedException when validating custom JWT claims
Ensure that your custom JWT Filter or AuthenticationEntryPoint returns a serialized JSON payload containing custom error statuses instead of letting the servlet container crash.
Custom filter does not execute in the correct sequence
Explicitly arrange your filter chain inside the SecurityFilterChain configuration using methods like http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class).
CORS configuration ignored or bypassed by Spring Security
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.
Related Resources
REST API Tester
Test API routes and endpoints directly in your browser with full request controls.
JSON Formatter & Validator
Beautify, validate, and minify JSON structures instantly.
Best Free Online Developer Tools
An expert review of must-have online utilities for developers.
Git Cheatsheet
Essential command reference for local and remote version control repositories.
Generated from LearnHubly Developer Cheatsheets
Access interactive sandbox tests, tools, and developer code bases at https://www.learnhubly.com