Java + Spring Security → Authentication & Authorization (Complete Guide)
Java + Spring Security → Authentication & Authorization (Complete Guide)
📌 Introduction
In modern applications, security is not optional — it's mandatory. Whether you're building enterprise apps, microservices, or SaaS platforms, authentication and authorization are the backbone of secure systems.
In the Java ecosystem, Spring Security is the most powerful and widely used framework for implementing security.
Spring Security provides robust support for authentication, authorization, and protection against attacks like CSRF, XSS, etc.
🖼️ Spring Security Architecture (Flow)
Spring Security works using a filter chain that processes every incoming request.
👉 Basic flow:
- Request → Security Filter Chain
- Authentication Filter extracts credentials
- Authentication Manager validates user
- UserDetailsService fetches user from DB
- SecurityContext stores authenticated user
- Request proceeds to Controller
This pipeline ensures every request is validated before accessing resources.
🔑 What is Authentication?
Authentication = Who are you?
It verifies user identity using:
- Username & Password
- OTP
- Tokens (JWT)
- OAuth / SSO
Example
User enters username + password → System verifies → Access granted
👉 In Spring Security:
- Managed by
AuthenticationManager - Uses
UserDetailsService - Passwords are encoded using
PasswordEncoder
🔐 What is Authorization?
Authorization = What can you do?
Once authenticated, the system checks:
- Roles (ADMIN, USER)
- Permissions (READ, WRITE)
Example
User is logged in → Can access /dashboard → Cannot access /admin
👉 Spring Security uses:
GrantedAuthority- Role-based access control (RBAC)
- Method-level security (
@PreAuthorize)
🔄 Authentication vs Authorization
| Feature | Authentication | Authorization |
|---|---|---|
| Purpose | Verify identity | Grant access |
| Happens | First | After authentication |
| Example | Login | Access control |
| Spring Component | AuthenticationManager | AccessDecisionManager |
⚙️ Spring Security Setup (Step-by-Step)
1️⃣ Add Dependency (Spring Boot)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2️⃣ Default Behavior
Once added:
- All endpoints are secured
- Default login page is generated
- Basic authentication enabled
3️⃣ Custom Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin();
return http.build();
}
}
4️⃣ In-Memory User Configuration
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User
.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
5️⃣ Password Encoder
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
🖼️ Authentication Flow (Detailed)
👉 Internally:
- Credentials → Authentication Filter
- Passed to → AuthenticationManager
- Delegates to → AuthenticationProvider
- Fetch user → UserDetailsService
- Validate → PasswordEncoder
If valid → stored in SecurityContextHolder
🔐 JWT Authentication (Modern Approach)
Instead of sessions, modern apps use JWT (JSON Web Tokens):
Flow:
- User logs in → gets token
- Token sent in headers
- Server validates token
- Access granted
👉 Benefits:
- Stateless
- Scalable (microservices)
- No session storage needed
JWT is widely used with Spring Security for modern APIs.
🔒 Common Security Features in Spring Security
- CSRF Protection
- Session Management
- OAuth2 / OpenID Connect
- Role-based Access Control
- Method-level Security
- Password Encryption
Spring Security integrates deeply with Spring Boot and supports multiple standards like OAuth2 and SAML.
🚀 Real-World Use Cases
- Banking Applications
- E-commerce Platforms
- Enterprise Workflow Systems (Camunda, JBPM)
- SaaS Products
- Microservices APIs
⚠️ Best Practices
✅ Always encode passwords (BCrypt)
✅ Use HTTPS
✅ Avoid hardcoded credentials
✅ Implement JWT for APIs
✅ Enable CSRF protection
✅ Use role-based authorization
🔗 Reference Articles
- Camunda Security Concepts
- Workflow Authorization in BPM
- REST API Security Best Practices
👉 Example reference:
🔗 http://shikhanirankari.blogspot.com/
French version: https://shikhanirankari.blogspot.com/2026/04/java-spring-security-authentification.html
🏁 Conclusion
Spring Security makes it easy to implement enterprise-grade security in Java applications.
- Authentication ensures identity
- Authorization ensures access control
- Together → build secure, scalable systems
💼 Need Help with Spring Security, Authentication, or Backend Systems?
I help teams design secure applications, fix production issues, and build scalable Java-based systems.
Services include:
- Spring Security implementation
- Authentication & Authorization (JWT, OAuth2)
- API security & performance tuning
- Enterprise backend architecture (Java, Microservices, Camunda)
🔗 https://shikhanirankari.blogspot.com/p/professional-services.html
📩 Email: ishikhanirankari@gmail.com | info@realtechnologiesindia.com
🌐 https://realtechnologiesindia.com
✔ Available for quick consulting calls
✔ Response within 24 hours
Comments
Post a Comment