Authentication
About
Authentication is the process of verifying the identity of a user or system before granting access. It ensures that the user is who they claim to be by checking credentials such as:
Username & password (most common method)
Token-based authentication (e.g., JWT, OAuth2)
Multi-factor authentication (MFA) (e.g., OTP, fingerprint, etc.)
Example
If we log in to a website using our email and password, authentication verifies whether our credentials are correct.
If correct → We are authenticated and granted access.
If incorrect → Access is denied.
How Authentication Flow Works
Let’s break down how authentication works in simple terms -
User provides credentials (e.g., username/password in a login form).
Spring Security intercepts the request and checks for authentication.
AuthenticationManager verifies credentials using an Authentication Provider (e.g., DAOAuthenticationProvider).
UserDetailsService loads user details from a database (if required).
PasswordEncoder checks if the password matches (e.g., BCrypt).
If successful, a Security Context is created, and the user is marked as authenticated.
User gains access to the requested resource.
If authentication fails, Spring Security denies access.
Authentication & Authorization
What it does
Confirms who you are
Confirms what you can do
Purpose
Identity verification
Access control
Example
Logging into a website
Checking if you can access an admin panel
Data used
Username, password, tokens
Roles, permissions
Enforced by
AuthenticationManager
Access Control mechanisms (like roles & permissions)
How Spring Security Handles Authentication
Spring Security provides a built-in authentication system that works as follows -
Intercepts authentication requests using filters.
Delegates authentication to an AuthenticationManager.
Validates credentials via Authentication Providers.
Stores authentication details in SecurityContextHolder.
Manages user sessions & permissions.
Spring Security supports multiple authentication methods, including -
Form-based login
HTTP Basic Authentication
JWT-based authentication
OAuth2 & OpenID Connect
Multi-factor authentication
Custom Authentication Providers in Spring Security
By default, Spring Security uses DaoAuthenticationProvider
to authenticate users against a database.
However, we can create a custom authentication provider when -
Authenticating users via an external system (e.g., LDAP, OAuth, API).
Using a custom password verification logic.
Handling multi-factor authentication (MFA).
Last updated
Was this helpful?