Let’s understand how Spring Security handles authentication behind the scenes — step by step.
Imagine a user is trying to log in by entering a username and password on a login page.
The first thing that happens is — the user’s login request is captured by something called the Authentication Filter.
This filter is responsible for reading the login form, extracting the username and password, and wrapping them into an object called the Authentication Object.
You can think of this as a request envelope containing the user’s credentials.
Now, this Authentication Object is sent to the Authentication Manager.
The Authentication Manager doesn’t validate anything by itself.
Instead, it’s like a traffic controller — it delegates the work to one or more Authentication Providers.
Each Authentication Provider is designed to handle a specific kind of login.
For example:
One provider may handle the username and password,
Another might handle OAuth2 tokens,
And another could support LDAP authentication.
The Authentication Manager checks which provider supports the given type of credentials using the supports() method.
Once it finds a match, it calls that provider’s authenticate() method to actually verify the user’s identity.
Once it finds a match, it passes the request to that provider’s authenticate() method.
Inside the Authentication Provider, Spring Security uses something called the UserDetailsService.
This service is responsible for looking up the user from the database based on the username.
It calls a method named loadUserByUsername() — and retrieves a UserDetails object.
This object contains all the important information like:
The actual username,
The encrypted password,
And the user’s roles or permissions.
If the password matches and everything checks out, the provider creates a new Authentication Object, this time filled with authenticated user details — also called the Principal.
This authenticated object is then returned all the way back to the Authentication Filter.
Spring Security now knows: “Yes, this user is verified.”
Finally, Spring Security stores this authenticated user inside the SecurityContext.
This context stays available throughout the session or request, so that every time the user accesses a protected URL, Spring knows who they are and what they’re allowed to do.
コメント