SRaj
SRaj

Reputation: 1338

Spring Security Authentication and User Interfaces

According to Spring Security, Authentication Provider is used if the authentication is done by an external Authentication Provider. After Authentication, Spring Security will get the Authentication object which encapsulates the user information.

If Spring Security framework authenticates, the user information is encapsulated in an instance of User interface (for example UserDetails class which is a default implementation).

My question is - why Spring Security framework couldn't use a consistent approach? Why they could not use UserDetails instead of Authentication object for all the cases? Is there any reason for that?

Upvotes: 1

Views: 258

Answers (1)

Pradyskumar
Pradyskumar

Reputation: 336

According to Spring documentation

public interface Authentication extends Principal, Serializable

Represents the token for an authentication request or for an authenticated principal once the request has been processed by the AuthenticationManager.authenticate(Authentication) method. Once the request has been authenticated, the Authentication will usually be stored in a thread-local SecurityContext managed by the SecurityContextHolder by the authentication mechanism which is being used. An explicit authentication can be achieved, without using one of Spring Security's authentication mechanisms, by creating an Authentication instance and using the code:

 SecurityContextHolder.getContext().setAuthentication(anAuthentication);

For more details, refer https://docs.spring.io/spring-security/site/docs/4.2.15.RELEASE/apidocs/org/springframework/security/core/Authentication.html

Explanation:

Authentication object will be set to local security context only if the user is authenticated with valid credentials. And it acts as a token. Where as in case of UserDetails we can't get to know if the user is authenticated.

You can also look at it as a Single Responsibility Principle, Where UserDetails class resposnibility is to manage user details, Authentication Responsibility is to handle authenticity.

Upvotes: 1

Related Questions