Roles vs. Authorities: The Distinction That Matters Spring Security uses one interface for both roles and authorities: GrantedAuthority. Both are just strings. The difference is convention. Authority: a fine-grained permission string — user:read, report:export, order:cancel Role: a coarse-grained label that groups authorities — ROLE_ADMIN, ROLE_MANAGER, ROLE_USER The ROLE_ prefix is the only mechanical difference. When you call hasRole("ADMIN"), Spring Security prepends ROLE_ automatically and checks for ROLE_ADMIN. When you call hasAuthority("ROLE_ADMIN") you must include the prefix yourself.
Continue reading »Spring Security Tutorial
30 posts in this section
Security Headers: CSP, HSTS, Clickjacking Protection
Why Security Headers Matter Security headers tell browsers how to behave when handling your content. They stop entire classes of attacks — XSS, clickjacking, protocol downgrade, information leakage — with a few lines of configuration. They cost nothing at runtime and are one of the highest-value-per-effort security improvements available. Spring Security’s Default Headers Spring Security adds a set of secure headers by default. You do not need any explicit configuration to get them:
Continue reading »SecurityContext and Authentication Object
The SecurityContext Is the Source of Truth Every security decision in Spring Security ultimately comes down to one question: “What Authentication object is stored in the SecurityContext?” Does the user have ROLE_ADMIN? → check Authentication.getAuthorities() What is the user’s ID? → cast Authentication.getPrincipal() to UserDetails Is the user logged in at all? → check Authentication.isAuthenticated() Understanding the SecurityContext and Authentication is not optional — it underlies everything. The Object Hierarchy classDiagram class SecurityContextHolder { -strategy: SecurityContextHolderStrategy +getContext() SecurityContext +setContext(SecurityContext context) +clearContext() +getContextHolderStrategy() SecurityContextHolderStrategy } class SecurityContext { <> +getAuthentication() Authentication +setAuthentication(Authentication authentication) } class Authentication { <> +getPrincipal() Object +getCredentials() Object +getAuthorities() Collection~GrantedAuthority~ +getDetails() Object +isAuthenticated() boolean +getName() String } class UsernamePasswordAuthenticationToken { +UsernamePasswordAuthenticationToken(principal, credentials) +UsernamePasswordAuthenticationToken(principal, credentials, authorities) } class GrantedAuthority { <> +getAuthority() String } class SimpleGrantedAuthority { -role: String +getAuthority() String } SecurityContextHolder --> SecurityContext SecurityContext --> Authentication Authentication <|.
Continue reading »SecurityFilterChain Bean: The Modern Configuration API
The Modern Configuration Model Spring Security 6.x dropped WebSecurityConfigurerAdapter. The new model uses a SecurityFilterChain @Bean directly. This is not just a syntax change — it’s a fundamentally cleaner design: Old approach New approach Extend WebSecurityConfigurerAdapter @Bean SecurityFilterChain method Override configure(HttpSecurity) Accept HttpSecurity parameter Chain with .and() Lambda DSL — each concern is a separate block One class per application Multiple beans, one per URL namespace Implicit global AuthenticationManager Explicit AuthenticationManager bean // OLD — don't do this @Configuration public class OldSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.
Continue reading »Session Management: Fixation, Concurrency, and Redis Sessions
How Spring Security Uses Sessions For form login and traditional web applications, Spring Security stores the Authentication object in the HTTP session. On every request, SecurityContextPersistenceFilter (Spring Security 5) or SecurityContextHolderFilter (Spring Security 6) loads the SecurityContext from the session and puts it in the SecurityContextHolder. For stateless APIs using JWT or OAuth2 Bearer tokens, no session is created — the token is verified on every request. Session Creation Policy Control when Spring Security creates sessions:
Continue reading »Spring Authorization Server: Build Your Own OAuth2 Server
What Is Spring Authorization Server? Spring Authorization Server (SAS) is an official Spring project that implements OAuth 2.1 and OpenID Connect 1.0 as a Spring Boot application. It provides a complete authorization server you can host yourself — issuing tokens for your own clients and APIs. Use it when: You want SSO across your own microservices You cannot use a hosted provider (Okta, Auth0) due to compliance or cost You need complete control over token format and claims You’re building a platform where other apps authenticate against your identity service Architecture flowchart TD SPA[SPA / Mobile App\nOAuth2 Client] -->|Authorization Code + PKCE| SAS Service[Backend Service\nClient Credentials| SAS] SAS[Spring Authorization Server\nIssues tokens] RS1[Your REST API\nResource Server] -->|Validates JWT| SAS RS2[Another API\nResource Server] -->|Validates JWT| SAS SAS -->|Signs tokens with| PK[Private Key\nJWK Set at /.
Continue reading »Spring Security Best Practices and Production Checklist
Using This Reference This is the final article in the Spring Security series. It is a consolidated reference — not a tutorial. Come back to this checklist before every launch and when reviewing a new codebase. Each item links back to the relevant article in the series. 1. Keep Spring Security Updated Security vulnerabilities in Spring Security itself are rare but severe when they occur. A dependency that is one minor version behind can expose known CVEs.
Continue reading »Testing Spring Security: @WithMockUser, MockMvc, and SecurityMockMvc
Why Security Tests Are Non-Negotiable A security configuration that is never tested is a security configuration that is probably wrong. URL patterns have subtle ordering rules. Method security annotations are silently ignored if @EnableMethodSecurity is missing. CSRF tokens must be present in the right form. Testing is the only way to know your authorization rules are actually enforced. Test Dependencies <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> @WithMockUser The simplest way to simulate an authenticated user.
Continue reading »The Security Filter Chain: Every Filter Explained
Every Filter Has a Job The Spring Security filter chain is not a monolith — it’s 15-20 individual filters, each responsible for exactly one concern. Understanding each filter’s job means you can: Know exactly where in the chain a request fails Add your own filter in the right position Remove filters you don’t need for performance Debug authentication and authorization problems The Complete Filter Order Spring Security defines a strict ordering for its filters.
Continue reading »X.509 Certificate Authentication
What Is X.509 Authentication? X.509 authentication (also called mutual TLS or mTLS) uses digital certificates instead of passwords. The client presents a certificate during the TLS handshake. The server verifies the certificate against a trusted Certificate Authority (CA) and extracts the user identity from the certificate’s Common Name (CN) or Subject Alternative Name (SAN). sequenceDiagram participant Client as Client (with certificate) participant Server as Spring Boot Server Client->>Server: TLS ClientHello Server->>Client: TLS ServerHello + Server Certificate Server->>Client: CertificateRequest (ask for client cert) Client->>Server: Client Certificate + CertificateVerify Server->>Server: Verify against trusted CA Server->>Server: Extract CN from certificate: "
Continue reading »