Spring
Security
Deep dive
into basics
Spring Security 2025
About me
Senior Engineer | Architect @ Avenga
Passionate about System Architecture and Software
Engineering
Spring Security 2025
LinkedIn: https://www.linkedin.com/in/ihor-polataiko
Medium: https://medium.com/@ihor.polataiko
GitHub: https://github.com/Igor-Polatajko
Exploration of out-of-the-box Spring Security authentication
mechanisms and their customization points
Modularization of security configurations
Setup of simple custom authentication mechanism for REST API
Overview of the essential elements of any Spring Security
authentication mechanism
Setup of custom authentication mechanism for REST API
supporting different types of authentication: JWT and API Key
Combination different security setups in one project
Recap and Recommendations
Agenda
01
03
05
02
04
06
07
Spring Security
Architecture
Overview
Spring Security is a part of the Spring Framework
intended for implementing application-level
security: mainly authentication and authorization
mechanisms
Proper understanding of the main building blocks
of the Spring Security (aka “Basics of Spring
Security”) will let you to be confident with any
Spring Security setup
Many engineers would agree, that Spring Security
is one of the most challenging parts of Spring
Framework
Spring Security Overview
Spring Security Filters
Spring Security authentication / authorization logic operates
mainly at the Filter(s) level
Types of filters:
● Authentication filters
● AuthorizationFilter
● Other filters
(e.g., attack-protection,
security session, exceptions
translations, ect)
Spring Web application
Filters
Dispatcher
Servlet
Controllers
Client
Spring Security Filters
Spring Security authentication / authorization logic operates
mainly at the Filter(s) level
Types of filters:
● Authentication filters
● AuthorizationFilter
● Other filters
(e.g., attack-protection,
security session, exceptions
translations, ect)
And Spring Interceptors for method
security (“@PreAuthorize”)
Spring Web application
Filters
Dispatcher
Servlet
Controllers
Client
Spring
Interceptors
* application might have many SecurityFilterChain(s) registered
** only one SecurityFilterChain can be applied for “securing” a specific request
SecurityFilterChain
Client
Spring Web application
Dispatcher
Servlet
Controllers
Spring Security Filter Chain
Basic
Authentication
Filter
Username
Password
Filter
…
Exception
Translation
Filter
Authorization
Filter
● HttpSecurity — builder of SecurityFilterChain
● HttpSecurity is creating instance of
DefaultSecurityFilterChain
● HttpSecurity is registered as a Spring Bean by
Spring Security, so it can be injected
(most of the time, into the @Bean-annotated
method of a @Configuration class)
● SecurityFilterChain should be registered as
a bean for Spring Security to “pick it up”
HttpSecurity
Authentication data transfer
Client
Spring Web application
Authentication
Filters
Authorization
Filter
Method
Security
Interceptors
Controllers
Authentication
Security Context
Security Context
Holder
Set
‘authenticated’
Authentication
with the details
about the
authenticated
user
Use Authentication
object to perform
authorization logic
Inject Authentication
or @Authentication
Prinsipal into
controller method
Authentication data transfer
Client
Spring Web application
Authentication
Filters
Authorization
Filter
Method
Security
Interceptors
Controllers
Authentication
Security Context
Security Context
Holder
●Authentication
(“unauthenticated” vs
“authenticated”)
Authentication data transfer
Client
Spring Web application
Authentication
Filters
Authorization
Filter
Method
Security
Interceptors
Controllers
Authentication
Security Context
Security Context
Holder
●Authentication
(“unauthenticated” vs
“authenticated”)
●Authentication
principal (inside
Authentication object)
Authentication
principal
Authentication data transfer
Client
Spring Web application
Authentication
Filters
Authorization
Filter
Method
Security
Interceptors
Controllers
Authentication
Security Context
Security Context
Holder
●Authentication
(“unauthenticated” vs
“authenticated”)
●Authentication
principal (inside
Authentication object)
●SecurityContext
Authentication
principal
Authentication data transfer
Client
Spring Web application
Authentication
Filters
Authorization
Filter
Method
Security
Interceptors
Controllers
Authentication
Security Context
Security Context
Holder
●Authentication
(“unauthenticated” vs
“authenticated”)
●Authentication
principal (inside
Authentication object)
●SecurityContext
●SecurityContextHolder
(* with Thread-local
strategy by default)
Authentication
principal
Authentication data transfer
Client
Spring Web application
Authentication
Filters
Authorization
Filter
Method
Security
Interceptors
Controllers
Authentication
Security Context
Security Context
Holder
Set
‘authenticated’
Authentication
with the details
about the
authenticated
user
●Authentication
(“unauthenticated” vs
“authenticated”)
●Authentication
principal (inside
Authentication object)
●SecurityContext
●SecurityContextHolder
(* with Thread-local
strategy by default)
Authentication
principal
Authentication data transfer
Client
Spring Web application
Authentication
Filters
Authorization
Filter
Method
Security
Interceptors
Controllers
Authentication
Security Context
Security Context
Holder
Set
‘authenticated’
Authentication
with the details
about the
authenticated
user
Inject Authentication
or @Authentication
Prinsipal into
controller method
●Authentication
(“unauthenticated” vs
“authenticated”)
●Authentication
principal (inside
Authentication object)
●SecurityContext
●SecurityContextHolder
(* with Thread-local
strategy by default)
Use Authentication
object to perform
authorization logic
Authentication
principal
● boolean isAuthenticated() — indicates if Authentication is “authenticated” (carries
data about authenticated request) or “unauthenticated” (carries request
authentication credentials)
● void setAuthenticated() — designed to allow for switch between
“unauthenticated” and “authenticated” states of Authentication
● Object getPrincipal() — returns data about authenticated user
● Collection<? extends GrantedAuthority> getAuthorities() — returns a list of
user roles (as a collection of GrantedAuthorities)
● getCredentials() — designed to transfer credentials in the “unauthenticated”
Authentication, when it’s used as a “credentials carrying bag for yet
unauthenticated request”.
● String getName() – designed to transfer the username of the user
● Object getDetails() — might be used for additional data about the request.
Authentication interface overview
Simple
setup
Simple Spring Security setup
1
2
3
REST API auth with token (JWT or Opaque token)
Opaque token - random string with no meaning
JWT - string with encoded content and signature
can be:
● read by anyone;
● verified by owner of the key (public key or
symmetric key);
● issued by owner of the key (private key or
symmetric key)]
Authentication requirements for the project:
Simple Spring Security setup (Opaque
token case)
Spring Web application
Authentication
Security Context
Security Context
Holder
SecurityAuthenticationFilters
1. Retrieves the value of the token from the
“Authorization” header
2. Looks up the AuthUser by the token in
AuthUserCache
3. If found, creates the object of UserAuthentication
and sets it into SecurityContextHolder; otherwise
throws and exception (instance of
AuthenticationException)
Client
Some
filters
Including AuthorizationFilter
Some
filters
Controllers
Public
login
endpoint
Secured
endpoints
Authentication contains
AuthUser
AuthUserCache
Contains map of
Token to
AuthUser
1
3
4
5
2
Try to get AuthUser
by token
Create “authenticated”
Authentication
Get
authentication
Get
authentication
Save the issued token and related user
auth data (AuthUser) server-side
Simple Spring Security setup (JWT)
Spring Web application
Authentication
Security Context
Security Context
Holder
SecurityAuthenticationFilters
1. Retrieves the value of the token from the
“Authorization” header
2. Verifies the JWT token
3. If valid, creates the object of UserAuthentication
and sets it into SecurityContextHolder; otherwise
throws an exception (instance of
AuthenticationException)
Client
Some
filters
Including AuthorizationFilter
Some
filters
Controllers
Public
login
endpoint
Secured
endpoints
Authentication contains
AuthUser
JwtService
Implements the
logic of creation
and verification of
JWT tokens
1
3
4
5
2
Try to get AuthUser
by token
Create “authenticated”
Authentication
Get
authentication
Get
authentication
Generate JWT token
Simple Spring Security setup (JWT)
● Custom class to carry data about authenticated user (AuthUser). This class is not required to implement any
interfaces in the particular setup
● Custom implementation of Authentication interface (UserAuthentication)
Simple Spring Security setup (JWT): Summary
Spring Security 2025
● Custom filter (SecurityAuthenticationFilter) to:
● Fetch authentication credentials (JWT token) from the request
● Check authentication rules (JWT token validation); throw instance of AuthenticationException if not
passed
● SecurityFilterChain bean configuration (via HttpSecurity) and registration
● Construct “authenticated” instance of Authentication (UserAuthentication) with authentication
principal (AuthUser)
● Wrap Authentication (UserAuthentication) into SecurityContext and set it into SecurityContextHolder
Out-of-the-box
mechanisms
Out-of-the-box authentication mechanisms
Basic out-of-the-box mechanisms:
● Form login -> UsernamePasswordAuthenticationFilter + UsernamePasswordAuthenticationToken
Spring Security 2025
● Http Basic -> BasicAuthenticationFilter + UsernamePasswordAuthenticationToken
Other out-of-the-box authentication mechanisms, such as OAuth, SAML, X509 require specific dependencies to
be added
Customization points of authentication logic:
● AuthenticationManager
● AuthenticationProvider -> uses ProviderManager implementation of AuthenticationManager
● UserDetailsService -> uses DaoAuthenticationProvider implementation of AuthenticationProvider
Convert “unauthenticated”
Authentication into
“authenticated” Authentication
Fetch user data by username
Convert “unauthenticated” Authentication
into “authenticated” Authentication
(many AuthenticationProvider(s) can be
registered)
Out-of-the-box authentication mechanisms
Authentication mechanism:
● Form login
Spring Security 2025
● Http Basic
Customization point:
● AuthenticationManager
● AuthenticationProvider
● UserDetailsService
Client
Spring Web application
Authentication
Security Context
Security Context
Holder
CustomAuthenticationManager
Our custom implementation of
AuthenticationManager which supports
the UsernamePasswordAuthentication
Token implementation of
Authentication
Some
filters
UsernamePasswordAuthenticationFilter
Some
filters
Controllers
Secured
endpoints
Including AuthorizationFilter
Authentication (of type
UsernamePasswordAuthenticationToken)
contains AuthUser (which, in this
example, is not required to implement
any interfaces)
Delegate to
AuthenticationManager
Set “authenticated”
Authentication
Get authentication
Get authentication
Out-of-the-box authentication mechanisms
Authentication mechanism:
● Form login
Spring Security 2025
● Http Basic
Customization point:
● AuthenticationManager
● AuthenticationProvider
● UserDetailsService
Client
Spring Web application
Authentication
Security Context
Security Context
Holder
UsernamePasswordAuthenticationProvider
Our custom implementation of
AuthenticationProvider that supports the
UsernamePasswordAuthenticationToken
implementation of Authentication
Some
filters
UsernamePasswordAuthenticationFilter
Some
filters
Controllers
Secured
endpoints
Including AuthorizationFilter
Authentication (of type
UsernamePasswordAuthenticationToken)
contains AuthUser (which, in this
example, is not required to implement
any interfaces)
Set “authenticated”
Authentication
Get authentication
Get authentication
ProviderManager
Delegate to
AuthenticationProvider
Delegate to
AuthenticationManager
Out-of-the-box authentication mechanisms
Authentication mechanism:
● Form login
Spring Security 2025
● Http Basic
Customization point:
● AuthenticationManager
● AuthenticationProvider
● UserDetailsService
Client
Spring Web application
Authentication
Security Context
Security Context
Holder
UserDetailsServicelmpl
Implements details of how user details data should be loaded
by user’s username. Class containing user data should
implement UserDetails interface
Some
filters
UsernamePasswordAuthenticationFilter
Some
filters
Controllers
Secured
endpoints
Including AuthorizationFilter
Authentication (of type
UsernamePasswordAuthenticationToken)
contains AuthUser (which, in this case,
should implement UserDetails interface)
Set “authenticated”
Authentication
Get authentication
Get authentication
ProviderManager
Delegate to
AuthenticationProvider
Delegate to
AuthenticationManager
DaoAuthenticationProvider
Return UserDetails
Load by username
Out-of-the-box authentication mechanisms
Authentication mechanism:
● Form login
Spring Security 2025
● Http Basic
Customization point:
● AuthenticationManager
● AuthenticationProvider
● UserDetailsService**
Client
Spring Web application
Authentication
Security Context
Security Context
Holder
InMemoryUserDetailsManager
<built-in implementation of UserDetailsService>
Some
filters
UsernamePasswordAuthenticationFilter
Some
filters
Controllers
Secured
endpoints
Including AuthorizationFilter
Authentication contains a built-in
implementation of UserDetails: class
“User”
Set “authenticated”
Authentication
Get authentication
Get authentication
ProviderManager
Delegate to
AuthenticationProvider
Delegate to
AuthenticationManager
DaoAuthenticationProvider
Return UserDetails
Load by username
Modularization of security
setup: Spring Security
Configurers
(or “How the magic works…”)
Spring Security Configurers
How do I know what is created by out-of-the-box mechanisms?
Well… I’ve just taken a look into their Configurers
Spring Security 2024
Spring Security Configurers provide modularization of
security configurations
Spring Security Configurers
Spring Security 2025
Spring Security Configurers
Spring Security 2025
Under the hoods of HttpSecurity:
My security config:
Spring Security Configurers
Spring Security 2025
My security config:
Under the hoods of HttpSecurity:
Spring Security Configurers
Spring Security 2025
My security config:
Under the hoods of HttpSecurity:
Spring Security Configurers
Spring Security 2025
My security config:
Under the hoods of HttpSecurity:
Spring Security Configurers: Contract
1
2
void init(B builder) – initializes the builder (HttpSecurity) with shared objects or
default settings required for later configuration
void configure(B builder) – applies specific security rules, settings, or
customizations to the builder (HttpSecurity)
Spring Security Configurers (used with HttpSecurity) should extend
AbstractHttpConfigurer
Spring Security Configurers: Example
Spring Security 2025
Spring Security Configurers: Example
Spring Security 2025
Form login [.formLogin(...)] FormLoginConfigurer
Spring Security 2025
Configurers of out-of-the-box
mechanisms
HTTP Basic [.httpBasic(...)] HttpBasicConfigurer
Registration of UserDetailsService
implementation [.userDetailsService(...)] DaoAuthenticationConfigurer
Reducing boilerplate
code in the custom
security filters
AuthenticationFilter
1
2
AuthenticationConverter implementation: fetch authentication credentials from request
[HttpServetRequest -> “unauthenticated” Authentication]
AuthenticationManager implementation: perform actual authentication logic
[“unauthenticated” Authentication -> “authenticated” Authentication]
Reduce the amount of boilerplate code
At minimum, you’d have to specify:
3 Success and Failure handlers (not required, but usually unavoidable)
AuthenticationFilter: Example by
extending
Spring Security 2025
AuthenticationFilter: Example by
directly instantiating
Spring Security 2025
Custom authentication
mechanism for REST API
(supporting different types of authentication:
JWT and API Key)
Supporting multiple authentication
mechanisms
1
2
REST API auth with JWT (e.g., for web/mobile clients)
REST API auth with API key (e.g., for backend app clients)
Authentication requirements for the project:
Supporting multiple authentication
mechanisms
01 Define Authentication implementations
Spring Security 2025
Implementation steps:
02 Define AuthenticationProvider implementations
03 Define Filter(s) [leverage AuthenticationFilter to reduce boilerplate code]
04 Create custom configurer for each authentication mechanism
Leverage “sharedObjects” from HttpSecurity (builder of SecurityFilterChain) to fetch
AuthenticationManager implementation
Supporting multiple authentication
mechanisms
Spring Security 2025
Combination of different
security setups in one
project
Combination of authentication
mechanisms in on project
1
2
REST API
● JWT (e.g., for mobile and web clients)
● API Key (e.g., for backend app clients)
Web app (server-side rendered multipage application)
● OAuth2.0 login (to allow login via Github)
● Form login (to allow login with “login” and “password”)
Project authentication requirements:
Combination of authentication mechanisms
in on project
1
2
REST API security
[Server side rendered] web application security
Two SecurityFilterChain(s):
Combination of authentication
mechanisms in on project
Spring Security 2025
Combination of authentication mechanisms in on project
As the result of the setup:
4 implementations of Authentication
● 2 custom: JwtAuthentication and ApiKeyAuthentication
● 2 from out-of-the-box mechanisms: OAuth2AuthenticationToken and UsernamePasswordAuthenticationToken
5+ configurers applied:
● 2 custom: JwtAuthenticationConfigurer and ApiKeyAuthenticationConfigurer
● 3 from out-of-the-box mechanisms: FormLoginConfigurer [.formLogin(...)], DaoAuthenticationConfigurer [.userDetailsService(...)], OAuth2LoginConfigurer
[.oauth2Login(...)]
5+ filters
● 2 custom: JwtAuthenticationFilter [JwtAuthenticationConfigurer] and ApiKeyAuthenticationFilter [ApiKeyAuthenticationConfigurer]
● 3 from out-of-the-box mechanisms: OAuth2AuthorizationRequestRedirectFilter [OAuth2LoginConfigurer], OAuth2LoginAuthenticationFilter
[OAuth2LoginConfigurer], UsernamePasswordAuthenticationFilter [FormLoginConfigurer]
6 AuthenticationProvider(s) registered
● 2 custom: JwtAuthenticationProvider [JwtAuthenticationConfigurer] and ApiKeyAuthenticationProvider [ApiKeyAuthenticationConfigurer]
● 3 from out-of-the-box mechanisms: OidcAuthorizationCodeAuthenticationProvider [OAuth2LoginConfigurer], OAuth2LoginAuthenticationProvider
[OAuth2LoginConfigurer], DaoAuthenticationProvider [DaoAuthenticationConfigurer]
● 1 default: AnonymousAuthenticationProvider [AnonymousConfigurer]
AuthUser was made compatible with both UserDetails and OAuth2User contracts (interfaces)
2 SecurityFilterChain beans were registered (each having its own AuthenticationManager!!)
Conclusion
Recap
DelegatingFilter
Proxy
Servlet Filters
Dispatcher Servlet
FilterChainProxy
Spring Security
Filter Chain
Use
Use
RequestMatcher
Use
(via SecurityFilterChain matches)
→
Exception
Translation
Filter
Basic Authentication
Filter
Username
Password
Filter
…
Authorization
Filter
FilterSecurityInterceptor
(removed from default chain in
v6)
Access Denied
Handler
Authentication
Entry Point
Authentication
Manager
Provider
Manager
Authentication
Provider
Dao
Authentication
Provider
User
Details
Service
In Memory
UserDetails
Manager
Jdbc
UserDetails
Manager
UserDetails
Authentication
Security
Context
SecurityContext
Holder
Spring Controller
@Authentication Principal
Spring Controller
@Authentication Parameter
authentication.getPrincipal()
Use
Create/authenticate
Create/authenticate
Use
Use
implements
Use
<on AccessDeniedException>
Use
<on AuthenticationException>
Use
Use
implement
s
implements implements
Method security
@PreAuthorize
…
Recap: SecurityFilterChain(s)
Recap: Authentication object
Recap: Out-of-the-box mechanisms
customization points
It depends…
Which setup is recommended?
Which setup is recommended?
It depends…
● Simple custom auth
Which setup is recommended?
It depends…
● Simple custom auth -> Filter (leveraging AuthenticationFilter is
recommended) + Authentication (creating custom implementation is highly
recommended)
Which setup is recommended?
It depends…
● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) +
Authentication (creating custom implementation is highly recommended)
● OAuth / OIDC, Form login, SAML, HTTP Basic
Which setup is recommended?
It depends…
● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) +
Authentication (creating custom implementation is highly recommended)
● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers +
customization points (AuthenticationManager | AuthenticationProvider |
UserDetailsService or similar)
Which setup is recommended?
It depends…
● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) +
Authentication (creating custom implementation is highly recommended)
● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers +
customization points (AuthenticationManager | AuthenticationProvider |
UserDetailsService or similar)
● Combination of different authentication mechanisms
Which setup is recommended?
It depends…
● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) +
Authentication (creating custom implementation is highly recommended)
● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers +
customization points (AuthenticationManager | AuthenticationProvider |
UserDetailsService or similar)
● Combination of different authentication mechanisms -> Filter(s) +
Authentication(s) + AuthenticationProvider(s) (defining custom configurers
is recommended)
Which setup is recommended?
It depends…
● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) +
Authentication (creating custom implementation is highly recommended)
● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers +
customization points (AuthenticationManager | AuthenticationProvider |
UserDetailsService or similar)
● Combination of different authentication mechanisms -> Filter(s) +
Authentication(s) + AuthenticationProvider(s) (creating custom configurers is
recommended)
● Completely different/independent security setups in one project
Which setup is recommended?
It depends…
● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) +
Authentication (creating custom implementation is highly recommended)
● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers +
customization points (AuthenticationManager | AuthenticationProvider |
UserDetailsService or similar)
● Combination of different authentication mechanisms -> Filter(s) +
Authentication(s) + AuthenticationProvider(s) (creating custom configurers is
recommended)
● Completely different/independent security setups in one project -> Different
SecurityFilterChain beans
Q&A
Spring Security series on Medium:
https://bit.ly/3W2SlDO
Code on Github:
https://bit.ly/4h35GV4
Thank you for your attention

Spring Security: Deep dive into basics. Ihor Polataiko.pptx

  • 1.
  • 2.
    About me Senior Engineer| Architect @ Avenga Passionate about System Architecture and Software Engineering Spring Security 2025 LinkedIn: https://www.linkedin.com/in/ihor-polataiko Medium: https://medium.com/@ihor.polataiko GitHub: https://github.com/Igor-Polatajko
  • 3.
    Exploration of out-of-the-boxSpring Security authentication mechanisms and their customization points Modularization of security configurations Setup of simple custom authentication mechanism for REST API Overview of the essential elements of any Spring Security authentication mechanism Setup of custom authentication mechanism for REST API supporting different types of authentication: JWT and API Key Combination different security setups in one project Recap and Recommendations Agenda 01 03 05 02 04 06 07
  • 4.
  • 5.
    Spring Security isa part of the Spring Framework intended for implementing application-level security: mainly authentication and authorization mechanisms Proper understanding of the main building blocks of the Spring Security (aka “Basics of Spring Security”) will let you to be confident with any Spring Security setup Many engineers would agree, that Spring Security is one of the most challenging parts of Spring Framework Spring Security Overview
  • 6.
    Spring Security Filters SpringSecurity authentication / authorization logic operates mainly at the Filter(s) level Types of filters: ● Authentication filters ● AuthorizationFilter ● Other filters (e.g., attack-protection, security session, exceptions translations, ect) Spring Web application Filters Dispatcher Servlet Controllers Client
  • 7.
    Spring Security Filters SpringSecurity authentication / authorization logic operates mainly at the Filter(s) level Types of filters: ● Authentication filters ● AuthorizationFilter ● Other filters (e.g., attack-protection, security session, exceptions translations, ect) And Spring Interceptors for method security (“@PreAuthorize”) Spring Web application Filters Dispatcher Servlet Controllers Client Spring Interceptors
  • 8.
    * application mighthave many SecurityFilterChain(s) registered ** only one SecurityFilterChain can be applied for “securing” a specific request SecurityFilterChain Client Spring Web application Dispatcher Servlet Controllers Spring Security Filter Chain Basic Authentication Filter Username Password Filter … Exception Translation Filter Authorization Filter
  • 9.
    ● HttpSecurity —builder of SecurityFilterChain ● HttpSecurity is creating instance of DefaultSecurityFilterChain ● HttpSecurity is registered as a Spring Bean by Spring Security, so it can be injected (most of the time, into the @Bean-annotated method of a @Configuration class) ● SecurityFilterChain should be registered as a bean for Spring Security to “pick it up” HttpSecurity
  • 10.
    Authentication data transfer Client SpringWeb application Authentication Filters Authorization Filter Method Security Interceptors Controllers Authentication Security Context Security Context Holder Set ‘authenticated’ Authentication with the details about the authenticated user Use Authentication object to perform authorization logic Inject Authentication or @Authentication Prinsipal into controller method
  • 11.
    Authentication data transfer Client SpringWeb application Authentication Filters Authorization Filter Method Security Interceptors Controllers Authentication Security Context Security Context Holder ●Authentication (“unauthenticated” vs “authenticated”)
  • 12.
    Authentication data transfer Client SpringWeb application Authentication Filters Authorization Filter Method Security Interceptors Controllers Authentication Security Context Security Context Holder ●Authentication (“unauthenticated” vs “authenticated”) ●Authentication principal (inside Authentication object) Authentication principal
  • 13.
    Authentication data transfer Client SpringWeb application Authentication Filters Authorization Filter Method Security Interceptors Controllers Authentication Security Context Security Context Holder ●Authentication (“unauthenticated” vs “authenticated”) ●Authentication principal (inside Authentication object) ●SecurityContext Authentication principal
  • 14.
    Authentication data transfer Client SpringWeb application Authentication Filters Authorization Filter Method Security Interceptors Controllers Authentication Security Context Security Context Holder ●Authentication (“unauthenticated” vs “authenticated”) ●Authentication principal (inside Authentication object) ●SecurityContext ●SecurityContextHolder (* with Thread-local strategy by default) Authentication principal
  • 15.
    Authentication data transfer Client SpringWeb application Authentication Filters Authorization Filter Method Security Interceptors Controllers Authentication Security Context Security Context Holder Set ‘authenticated’ Authentication with the details about the authenticated user ●Authentication (“unauthenticated” vs “authenticated”) ●Authentication principal (inside Authentication object) ●SecurityContext ●SecurityContextHolder (* with Thread-local strategy by default) Authentication principal
  • 16.
    Authentication data transfer Client SpringWeb application Authentication Filters Authorization Filter Method Security Interceptors Controllers Authentication Security Context Security Context Holder Set ‘authenticated’ Authentication with the details about the authenticated user Inject Authentication or @Authentication Prinsipal into controller method ●Authentication (“unauthenticated” vs “authenticated”) ●Authentication principal (inside Authentication object) ●SecurityContext ●SecurityContextHolder (* with Thread-local strategy by default) Use Authentication object to perform authorization logic Authentication principal
  • 17.
    ● boolean isAuthenticated()— indicates if Authentication is “authenticated” (carries data about authenticated request) or “unauthenticated” (carries request authentication credentials) ● void setAuthenticated() — designed to allow for switch between “unauthenticated” and “authenticated” states of Authentication ● Object getPrincipal() — returns data about authenticated user ● Collection<? extends GrantedAuthority> getAuthorities() — returns a list of user roles (as a collection of GrantedAuthorities) ● getCredentials() — designed to transfer credentials in the “unauthenticated” Authentication, when it’s used as a “credentials carrying bag for yet unauthenticated request”. ● String getName() – designed to transfer the username of the user ● Object getDetails() — might be used for additional data about the request. Authentication interface overview
  • 18.
  • 19.
    Simple Spring Securitysetup 1 2 3 REST API auth with token (JWT or Opaque token) Opaque token - random string with no meaning JWT - string with encoded content and signature can be: ● read by anyone; ● verified by owner of the key (public key or symmetric key); ● issued by owner of the key (private key or symmetric key)] Authentication requirements for the project:
  • 20.
    Simple Spring Securitysetup (Opaque token case) Spring Web application Authentication Security Context Security Context Holder SecurityAuthenticationFilters 1. Retrieves the value of the token from the “Authorization” header 2. Looks up the AuthUser by the token in AuthUserCache 3. If found, creates the object of UserAuthentication and sets it into SecurityContextHolder; otherwise throws and exception (instance of AuthenticationException) Client Some filters Including AuthorizationFilter Some filters Controllers Public login endpoint Secured endpoints Authentication contains AuthUser AuthUserCache Contains map of Token to AuthUser 1 3 4 5 2 Try to get AuthUser by token Create “authenticated” Authentication Get authentication Get authentication Save the issued token and related user auth data (AuthUser) server-side
  • 21.
    Simple Spring Securitysetup (JWT) Spring Web application Authentication Security Context Security Context Holder SecurityAuthenticationFilters 1. Retrieves the value of the token from the “Authorization” header 2. Verifies the JWT token 3. If valid, creates the object of UserAuthentication and sets it into SecurityContextHolder; otherwise throws an exception (instance of AuthenticationException) Client Some filters Including AuthorizationFilter Some filters Controllers Public login endpoint Secured endpoints Authentication contains AuthUser JwtService Implements the logic of creation and verification of JWT tokens 1 3 4 5 2 Try to get AuthUser by token Create “authenticated” Authentication Get authentication Get authentication Generate JWT token
  • 22.
  • 23.
    ● Custom classto carry data about authenticated user (AuthUser). This class is not required to implement any interfaces in the particular setup ● Custom implementation of Authentication interface (UserAuthentication) Simple Spring Security setup (JWT): Summary Spring Security 2025 ● Custom filter (SecurityAuthenticationFilter) to: ● Fetch authentication credentials (JWT token) from the request ● Check authentication rules (JWT token validation); throw instance of AuthenticationException if not passed ● SecurityFilterChain bean configuration (via HttpSecurity) and registration ● Construct “authenticated” instance of Authentication (UserAuthentication) with authentication principal (AuthUser) ● Wrap Authentication (UserAuthentication) into SecurityContext and set it into SecurityContextHolder
  • 24.
  • 25.
    Out-of-the-box authentication mechanisms Basicout-of-the-box mechanisms: ● Form login -> UsernamePasswordAuthenticationFilter + UsernamePasswordAuthenticationToken Spring Security 2025 ● Http Basic -> BasicAuthenticationFilter + UsernamePasswordAuthenticationToken Other out-of-the-box authentication mechanisms, such as OAuth, SAML, X509 require specific dependencies to be added Customization points of authentication logic: ● AuthenticationManager ● AuthenticationProvider -> uses ProviderManager implementation of AuthenticationManager ● UserDetailsService -> uses DaoAuthenticationProvider implementation of AuthenticationProvider Convert “unauthenticated” Authentication into “authenticated” Authentication Fetch user data by username Convert “unauthenticated” Authentication into “authenticated” Authentication (many AuthenticationProvider(s) can be registered)
  • 26.
    Out-of-the-box authentication mechanisms Authenticationmechanism: ● Form login Spring Security 2025 ● Http Basic Customization point: ● AuthenticationManager ● AuthenticationProvider ● UserDetailsService Client Spring Web application Authentication Security Context Security Context Holder CustomAuthenticationManager Our custom implementation of AuthenticationManager which supports the UsernamePasswordAuthentication Token implementation of Authentication Some filters UsernamePasswordAuthenticationFilter Some filters Controllers Secured endpoints Including AuthorizationFilter Authentication (of type UsernamePasswordAuthenticationToken) contains AuthUser (which, in this example, is not required to implement any interfaces) Delegate to AuthenticationManager Set “authenticated” Authentication Get authentication Get authentication
  • 27.
    Out-of-the-box authentication mechanisms Authenticationmechanism: ● Form login Spring Security 2025 ● Http Basic Customization point: ● AuthenticationManager ● AuthenticationProvider ● UserDetailsService Client Spring Web application Authentication Security Context Security Context Holder UsernamePasswordAuthenticationProvider Our custom implementation of AuthenticationProvider that supports the UsernamePasswordAuthenticationToken implementation of Authentication Some filters UsernamePasswordAuthenticationFilter Some filters Controllers Secured endpoints Including AuthorizationFilter Authentication (of type UsernamePasswordAuthenticationToken) contains AuthUser (which, in this example, is not required to implement any interfaces) Set “authenticated” Authentication Get authentication Get authentication ProviderManager Delegate to AuthenticationProvider Delegate to AuthenticationManager
  • 28.
    Out-of-the-box authentication mechanisms Authenticationmechanism: ● Form login Spring Security 2025 ● Http Basic Customization point: ● AuthenticationManager ● AuthenticationProvider ● UserDetailsService Client Spring Web application Authentication Security Context Security Context Holder UserDetailsServicelmpl Implements details of how user details data should be loaded by user’s username. Class containing user data should implement UserDetails interface Some filters UsernamePasswordAuthenticationFilter Some filters Controllers Secured endpoints Including AuthorizationFilter Authentication (of type UsernamePasswordAuthenticationToken) contains AuthUser (which, in this case, should implement UserDetails interface) Set “authenticated” Authentication Get authentication Get authentication ProviderManager Delegate to AuthenticationProvider Delegate to AuthenticationManager DaoAuthenticationProvider Return UserDetails Load by username
  • 29.
    Out-of-the-box authentication mechanisms Authenticationmechanism: ● Form login Spring Security 2025 ● Http Basic Customization point: ● AuthenticationManager ● AuthenticationProvider ● UserDetailsService** Client Spring Web application Authentication Security Context Security Context Holder InMemoryUserDetailsManager <built-in implementation of UserDetailsService> Some filters UsernamePasswordAuthenticationFilter Some filters Controllers Secured endpoints Including AuthorizationFilter Authentication contains a built-in implementation of UserDetails: class “User” Set “authenticated” Authentication Get authentication Get authentication ProviderManager Delegate to AuthenticationProvider Delegate to AuthenticationManager DaoAuthenticationProvider Return UserDetails Load by username
  • 30.
    Modularization of security setup:Spring Security Configurers (or “How the magic works…”)
  • 31.
    Spring Security Configurers Howdo I know what is created by out-of-the-box mechanisms? Well… I’ve just taken a look into their Configurers Spring Security 2024 Spring Security Configurers provide modularization of security configurations
  • 32.
  • 33.
    Spring Security Configurers SpringSecurity 2025 Under the hoods of HttpSecurity: My security config:
  • 34.
    Spring Security Configurers SpringSecurity 2025 My security config: Under the hoods of HttpSecurity:
  • 35.
    Spring Security Configurers SpringSecurity 2025 My security config: Under the hoods of HttpSecurity:
  • 36.
    Spring Security Configurers SpringSecurity 2025 My security config: Under the hoods of HttpSecurity:
  • 37.
    Spring Security Configurers:Contract 1 2 void init(B builder) – initializes the builder (HttpSecurity) with shared objects or default settings required for later configuration void configure(B builder) – applies specific security rules, settings, or customizations to the builder (HttpSecurity) Spring Security Configurers (used with HttpSecurity) should extend AbstractHttpConfigurer
  • 38.
    Spring Security Configurers:Example Spring Security 2025
  • 39.
    Spring Security Configurers:Example Spring Security 2025
  • 40.
    Form login [.formLogin(...)]FormLoginConfigurer Spring Security 2025 Configurers of out-of-the-box mechanisms HTTP Basic [.httpBasic(...)] HttpBasicConfigurer Registration of UserDetailsService implementation [.userDetailsService(...)] DaoAuthenticationConfigurer
  • 41.
    Reducing boilerplate code inthe custom security filters
  • 42.
    AuthenticationFilter 1 2 AuthenticationConverter implementation: fetchauthentication credentials from request [HttpServetRequest -> “unauthenticated” Authentication] AuthenticationManager implementation: perform actual authentication logic [“unauthenticated” Authentication -> “authenticated” Authentication] Reduce the amount of boilerplate code At minimum, you’d have to specify: 3 Success and Failure handlers (not required, but usually unavoidable)
  • 43.
  • 44.
    AuthenticationFilter: Example by directlyinstantiating Spring Security 2025
  • 45.
    Custom authentication mechanism forREST API (supporting different types of authentication: JWT and API Key)
  • 46.
    Supporting multiple authentication mechanisms 1 2 RESTAPI auth with JWT (e.g., for web/mobile clients) REST API auth with API key (e.g., for backend app clients) Authentication requirements for the project:
  • 47.
    Supporting multiple authentication mechanisms 01Define Authentication implementations Spring Security 2025 Implementation steps: 02 Define AuthenticationProvider implementations 03 Define Filter(s) [leverage AuthenticationFilter to reduce boilerplate code] 04 Create custom configurer for each authentication mechanism Leverage “sharedObjects” from HttpSecurity (builder of SecurityFilterChain) to fetch AuthenticationManager implementation
  • 48.
  • 49.
    Combination of different securitysetups in one project
  • 50.
    Combination of authentication mechanismsin on project 1 2 REST API ● JWT (e.g., for mobile and web clients) ● API Key (e.g., for backend app clients) Web app (server-side rendered multipage application) ● OAuth2.0 login (to allow login via Github) ● Form login (to allow login with “login” and “password”) Project authentication requirements:
  • 51.
    Combination of authenticationmechanisms in on project 1 2 REST API security [Server side rendered] web application security Two SecurityFilterChain(s):
  • 52.
    Combination of authentication mechanismsin on project Spring Security 2025
  • 53.
    Combination of authenticationmechanisms in on project As the result of the setup: 4 implementations of Authentication ● 2 custom: JwtAuthentication and ApiKeyAuthentication ● 2 from out-of-the-box mechanisms: OAuth2AuthenticationToken and UsernamePasswordAuthenticationToken 5+ configurers applied: ● 2 custom: JwtAuthenticationConfigurer and ApiKeyAuthenticationConfigurer ● 3 from out-of-the-box mechanisms: FormLoginConfigurer [.formLogin(...)], DaoAuthenticationConfigurer [.userDetailsService(...)], OAuth2LoginConfigurer [.oauth2Login(...)] 5+ filters ● 2 custom: JwtAuthenticationFilter [JwtAuthenticationConfigurer] and ApiKeyAuthenticationFilter [ApiKeyAuthenticationConfigurer] ● 3 from out-of-the-box mechanisms: OAuth2AuthorizationRequestRedirectFilter [OAuth2LoginConfigurer], OAuth2LoginAuthenticationFilter [OAuth2LoginConfigurer], UsernamePasswordAuthenticationFilter [FormLoginConfigurer] 6 AuthenticationProvider(s) registered ● 2 custom: JwtAuthenticationProvider [JwtAuthenticationConfigurer] and ApiKeyAuthenticationProvider [ApiKeyAuthenticationConfigurer] ● 3 from out-of-the-box mechanisms: OidcAuthorizationCodeAuthenticationProvider [OAuth2LoginConfigurer], OAuth2LoginAuthenticationProvider [OAuth2LoginConfigurer], DaoAuthenticationProvider [DaoAuthenticationConfigurer] ● 1 default: AnonymousAuthenticationProvider [AnonymousConfigurer] AuthUser was made compatible with both UserDetails and OAuth2User contracts (interfaces) 2 SecurityFilterChain beans were registered (each having its own AuthenticationManager!!)
  • 54.
  • 55.
    Recap DelegatingFilter Proxy Servlet Filters Dispatcher Servlet FilterChainProxy SpringSecurity Filter Chain Use Use RequestMatcher Use (via SecurityFilterChain matches) → Exception Translation Filter Basic Authentication Filter Username Password Filter … Authorization Filter FilterSecurityInterceptor (removed from default chain in v6) Access Denied Handler Authentication Entry Point Authentication Manager Provider Manager Authentication Provider Dao Authentication Provider User Details Service In Memory UserDetails Manager Jdbc UserDetails Manager UserDetails Authentication Security Context SecurityContext Holder Spring Controller @Authentication Principal Spring Controller @Authentication Parameter authentication.getPrincipal() Use Create/authenticate Create/authenticate Use Use implements Use <on AccessDeniedException> Use <on AuthenticationException> Use Use implement s implements implements Method security @PreAuthorize …
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
    Which setup isrecommended? It depends… ● Simple custom auth
  • 61.
    Which setup isrecommended? It depends… ● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) + Authentication (creating custom implementation is highly recommended)
  • 62.
    Which setup isrecommended? It depends… ● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) + Authentication (creating custom implementation is highly recommended) ● OAuth / OIDC, Form login, SAML, HTTP Basic
  • 63.
    Which setup isrecommended? It depends… ● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) + Authentication (creating custom implementation is highly recommended) ● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers + customization points (AuthenticationManager | AuthenticationProvider | UserDetailsService or similar)
  • 64.
    Which setup isrecommended? It depends… ● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) + Authentication (creating custom implementation is highly recommended) ● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers + customization points (AuthenticationManager | AuthenticationProvider | UserDetailsService or similar) ● Combination of different authentication mechanisms
  • 65.
    Which setup isrecommended? It depends… ● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) + Authentication (creating custom implementation is highly recommended) ● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers + customization points (AuthenticationManager | AuthenticationProvider | UserDetailsService or similar) ● Combination of different authentication mechanisms -> Filter(s) + Authentication(s) + AuthenticationProvider(s) (defining custom configurers is recommended)
  • 66.
    Which setup isrecommended? It depends… ● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) + Authentication (creating custom implementation is highly recommended) ● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers + customization points (AuthenticationManager | AuthenticationProvider | UserDetailsService or similar) ● Combination of different authentication mechanisms -> Filter(s) + Authentication(s) + AuthenticationProvider(s) (creating custom configurers is recommended) ● Completely different/independent security setups in one project
  • 67.
    Which setup isrecommended? It depends… ● Simple custom auth -> Filter (leveraging AuthenticationFilter is recommended) + Authentication (creating custom implementation is highly recommended) ● OAuth / OIDC, Form login, SAML, HTTP Basic -> Out-of-the-box configurers + customization points (AuthenticationManager | AuthenticationProvider | UserDetailsService or similar) ● Combination of different authentication mechanisms -> Filter(s) + Authentication(s) + AuthenticationProvider(s) (creating custom configurers is recommended) ● Completely different/independent security setups in one project -> Different SecurityFilterChain beans
  • 68.
  • 69.
    Spring Security serieson Medium: https://bit.ly/3W2SlDO Code on Github: https://bit.ly/4h35GV4 Thank you for your attention