What is Authentication in Spring Security?
Authentication in Spring Security is the process of verifying the identity of a user before allowing access to an application, API, or protected resource.
It ensures that the user is genuinely who they claim to be.
In simple words, authentication answers the question:
“Who are you?”
Why Authentication is Important
Modern applications contain sensitive data such as:
- User accounts
- Banking information
- Payment details
- Company records
- Personal information
Without authentication:
- Anyone can access private data
- Hackers may misuse APIs
- Unauthorized users may perform restricted actions
- Application security becomes weak
Authentication helps protect applications from unauthorized access.
Real-Life Authentication Example
Consider ATM banking:
- User inserts ATM card
- User enters PIN
- Bank verifies identity
- Access is granted
Here:
- ATM card → Username
- PIN → Password
- Verification → Authentication
Authentication in Web Applications
Common authentication methods:
- Username and password
- OTP verification
- JWT token authentication
- OAuth2 login
- Biometric authentication
Authentication Flow in Spring Security
Basic authentication process:
- User sends login credentials
- Spring Security receives request
- Credentials are validated
- User identity is verified
- Authentication object is created
- Access is granted
Main Components Involved in Authentication
| Component | Purpose |
|---|---|
| Authentication | Represents authenticated user |
| AuthenticationManager | Processes authentication |
| UserDetailsService | Loads user details |
| PasswordEncoder | Encrypts passwords |
| SecurityContext | Stores authenticated user details |
Spring Security Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Default Authentication in Spring Boot
After adding Spring Security dependency:
- All endpoints become secured
- Default login page is generated
- Username becomes
user - Random password appears in console
Example Console Password
Using generated security password:
5d2f3c8a-1234-9876-abcd
Simple Authentication Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest()
.authenticated()
)
.formLogin(Customizer.withDefaults());
return http.build();
}
}
How Authentication Works Internally
Internal authentication flow:
- User submits username and password
- Authentication filter intercepts request
- AuthenticationManager validates credentials
- UserDetailsService loads user data
- PasswordEncoder verifies password
- Authentication object is created
- SecurityContext stores authenticated user
What is Authentication Object?
Authentication object stores:
- Username
- Password
- User roles
- Authentication status
Authentication Example
Authentication authentication =
SecurityContextHolder
.getContext()
.getAuthentication();
String username = authentication.getName();
What is UserDetailsService?
UserDetailsService loads user information from:
- Database
- Memory
- External services
UserDetailsService Example
@Service
public class CustomUserDetailsService
implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(
String username)
throws UsernameNotFoundException {
return User.builder()
.username("admin")
.password(
passwordEncoder().encode("admin123")
)
.roles("ADMIN")
.build();
}
}
What is PasswordEncoder?
PasswordEncoder encrypts passwords before storing them.
Spring Security commonly uses:
- BCryptPasswordEncoder
PasswordEncoder Example
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Why Password Encryption is Important
Plain-text passwords are dangerous.
Encrypted passwords improve security by:
- Preventing password theft
- Protecting database leaks
- Reducing hacking risks
Authentication Using Database
Real-world applications usually store users in databases.
User Entity Example
@Entity
public class User {
@Id
private Long id;
private String username;
private String password;
private String role;
}
Repository Example
public interface UserRepository
extends JpaRepository<User, Long> {
Optional<User> findByUsername(
String username);
}
UserDetailsService Example
@Service
public class CustomUserDetailsService
implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(
String username) {
User user = userRepository
.findByUsername(username)
.orElseThrow(() ->
new UsernameNotFoundException(
"User Not Found"
));
return org.springframework.security.core.userdetails.User
.builder()
.username(user.getUsername())
.password(user.getPassword())
.roles(user.getRole())
.build();
}
}
Authentication Types in Spring Security
| Authentication Type | Description |
|---|---|
| Form Authentication | Username and password login |
| Basic Authentication | Browser-based authentication |
| JWT Authentication | Token-based authentication |
| OAuth2 Authentication | Google/GitHub login |
What is JWT Authentication?
JWT authentication uses tokens instead of sessions.
Flow:
- User logs in
- Server generates JWT token
- Client stores token
- Client sends token in every request
- Server validates token
JWT Header Example
Authorization: Bearer eyJhbGciOiJIUzI1Ni...
Authentication vs Authorization
| Feature | Authentication | Authorization |
|---|---|---|
| Main Purpose | Verify identity | Check permissions |
| Question | Who are you? | What can you access? |
| Occurs First | Yes | No |
Real-Time Example in Banking Application
Suppose a banking application has:
- Customer login
- Admin dashboard
- Money transfer APIs
Authentication process:
- User enters credentials
- Spring Security validates identity
- JWT token is generated
- User accesses secured APIs
Common Authentication Annotations
| Annotation | Purpose |
|---|---|
| @EnableWebSecurity | Enables Spring Security |
| @AuthenticationPrincipal | Access logged-in user |
| @PreAuthorize | Method-level security |
Access Logged-In User Example
@GetMapping("/profile")
public String profile(
@AuthenticationPrincipal UserDetails user) {
return user.getUsername();
}
Advantages of Authentication in Spring Security
- Protects sensitive resources
- Supports multiple authentication methods
- Provides enterprise-grade security
- Supports JWT and OAuth2
- Encrypts passwords securely
- Integrates well with REST APIs and microservices
Disadvantages of Authentication
- Complex configuration for beginners
- JWT implementation may become complicated
- Improper setup may create vulnerabilities
Best Practices for Authentication
- Always encrypt passwords using BCrypt
- Use HTTPS in production
- Implement JWT for APIs
- Use strong password policies
- Protect sensitive endpoints
- Implement proper session management
- Use refresh tokens securely
Common Authentication Exceptions
| Exception | Description |
|---|---|
| BadCredentialsException | Invalid username or password |
| UsernameNotFoundException | User not found |
| DisabledException | User account disabled |
| LockedException | User account locked |
Common Interview Questions on Authentication
What is authentication in Spring Security?
Authentication verifies the identity of users before granting access.
What is the role of UserDetailsService?
It loads user details from database or memory.
Why is PasswordEncoder important?
It encrypts passwords securely to prevent password theft.
What is the difference between authentication and authorization?
Authentication verifies identity, while authorization checks permissions.
Why is JWT authentication popular?
JWT is stateless, scalable, and ideal for REST APIs and microservices.
Conclusion
Authentication is one of the most important concepts in Spring Security. It verifies user identity before granting access to protected resources.
Spring Security provides multiple authentication mechanisms such as:
- Form login
- Basic authentication
- JWT authentication
- OAuth2 login
Proper authentication implementation improves application security, protects sensitive data, and supports enterprise-grade backend systems.
Understanding authentication is essential for Spring Boot developers because security is a mandatory requirement in modern web applications, REST APIs, and microservices.