Authentication vs Authorization in Java
Learn Authentication and Authorization in Java and Spring Security with real-world examples, diagrams, step-by-step implementation, role-based access control, and production best practices.
Introduction
Authentication and Authorization are two of the most important security concepts in every Java application.
Many developers use these terms interchangeably, but they solve completely different problems.
Authentication answers:
Who are you?
Authorization answers:
What are you allowed to do?
Every secure Java application must implement both.
Examples:
- Banking Applications
- Insurance Systems
- E-Commerce Platforms
- Healthcare Systems
- Enterprise Portals
Why This Topic Matters
Imagine a banking application.
Users:
- Customer
- Customer Support
- Manager
- Administrator
Not every user should have the same access.
flowchart TB
User["User"]
User --> Login["Authentication"]
Login --> Access["Authorization"]
Access --> CustomerAPI["Customer APIs"]
Access --> AdminAPI["Admin APIs"]
Without proper authentication and authorization:
❌ Unauthorized access
❌ Data leaks
❌ Privilege escalation
❌ Compliance violations
Authentication
Authentication verifies identity.
Example:
Username : venu
Password : ********
The system checks whether the credentials are valid.
sequenceDiagram
participant User
participant App
participant Database
User->>App: Username + Password
App->>Database: Verify Credentials
Database-->>App: User Found
App-->>User: Authentication Success
Result:
User Identity Verified
Authorization
Authorization happens after authentication.
Authorization determines what the authenticated user can access.
Example:
Authenticated User = venu
Role = USER
Can access:
/api/profile
/api/orders
Cannot access:
/api/admin/users
flowchart LR
AuthenticatedUser
--> Role
--> Permissions
--> ProtectedResource
Authentication vs Authorization
| Authentication | Authorization |
|---|---|
| Who are you? | What can you access? |
| Happens first | Happens after authentication |
| Verifies identity | Verifies permissions |
| Username/Password | Roles & Permissions |
| Returns User Identity | Returns Access Decision |
Real World Banking Example
Customer Login:
Username : venu
Password : ********
Authentication Success.
Now Authorization checks:
Role = CUSTOMER
Allowed:
View Accounts
Transfer Money
View Statements
Denied:
Manage Customers
Create Users
Delete Accounts
flowchart TB
Customer
--> Authentication
Authentication
--> Authorization
Authorization
--> CustomerAPIs
Authorization
--> DenyAdminAPIs
Authentication Flow
sequenceDiagram
participant Client
participant SecurityFilter
participant UserService
participant Database
Client->>SecurityFilter: Login Request
SecurityFilter->>UserService: Validate User
UserService->>Database: Find User
Database-->>UserService: User Record
UserService-->>SecurityFilter: User Verified
SecurityFilter-->>Client: Login Success
Authorization Flow
sequenceDiagram
participant User
participant Security
participant Controller
User->>Security: Access /admin/users
Security->>Security: Check Role
alt Has ADMIN Role
Security->>Controller: Allow
else Missing ADMIN Role
Security-->>User: 403 Forbidden
end
Authentication Mechanisms
Java applications commonly use:
mindmap
root((Authentication))
Username Password
JWT
OAuth2
OpenID Connect
LDAP
SAML
MFA
Authorization Models
Role Based Access Control (RBAC)
Most common model.
flowchart LR
User
--> Role
--> Permission
--> Resource
Example:
ADMIN
├── Create User
├── Delete User
└── Update User
USER
├── View Profile
└── Update Profile
Spring Security Architecture
flowchart TB
Client
--> SecurityFilterChain
--> AuthenticationManager
--> UserDetailsService
--> Database
Database --> UserDetailsService
UserDetailsService --> AuthenticationManager
AuthenticationManager --> SecurityFilterChain
SecurityFilterChain --> Controller
Spring Boot Project Setup
Dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
Step 1: Create Security Configuration
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**")
.hasRole("ADMIN")
.requestMatchers("/user/**")
.hasAnyRole("USER", "ADMIN")
.anyRequest()
.authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
Step 2: Create Users
@Bean
public UserDetailsService userDetailsService() {
UserDetails user =
User.withUsername("venu")
.password("{noop}password")
.roles("USER")
.build();
UserDetails admin =
User.withUsername("admin")
.password("{noop}admin")
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(
user,
admin
);
}
User Access Matrix
| API | USER | ADMIN |
|---|---|---|
| /public/health | ✅ | ✅ |
| /user/profile | ✅ | ✅ |
| /admin/users | ❌ | ✅ |
Step 3: Create Controller
@RestController
public class UserController {
@GetMapping("/public/health")
public String health() {
return "Healthy";
}
@GetMapping("/user/profile")
public String profile() {
return "User Profile";
}
@GetMapping("/admin/users")
public String users() {
return "Admin Users";
}
}
Access Flow
flowchart TB
Request
--> SecurityFilter
SecurityFilter
--> Authenticated
Authenticated
--> Authorized
Authorized
--> Controller
Controller
--> Response
Test Authentication
Public API:
curl http://localhost:8080/public/health
Response:
Healthy
User API:
curl -u venu:password \
http://localhost:8080/user/profile
Response:
User Profile
Admin API:
curl -u admin:admin \
http://localhost:8080/admin/users
Response:
Admin Users
Unauthorized Example
curl -u venu:password \
http://localhost:8080/admin/users
Response:
403 Forbidden
Method Level Authorization
Instead of securing URLs, we can secure methods.
Enable:
@EnableMethodSecurity
@Configuration
public class SecurityConfig {
}
Example:
@Service
public class UserService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
}
}
flowchart LR
Request
--> ServiceMethod
ServiceMethod
--> RoleCheck
RoleCheck
--> ExecuteMethod
Common Mistakes
Authentication Mistakes
❌ Plain text passwords
❌ No password hashing
❌ Weak passwords
❌ No MFA
Authorization Mistakes
❌ Everyone gets ADMIN role
❌ Missing role checks
❌ Exposed admin APIs
❌ Client-side authorization only
Production Best Practices
Authentication
- Use BCrypt
- Use JWT
- Use OAuth2
- Enable MFA
- Use HTTPS
Authorization
- RBAC
- Least Privilege
- Method Security
- API Security
Monitoring
- Audit Logs
- Failed Login Tracking
- Alerting
Authentication + Authorization Together
flowchart TB
LoginRequest
--> Authentication
Authentication
--> UserIdentity
UserIdentity
--> Authorization
Authorization
--> ResourceAccess
Authentication identifies the user.
Authorization determines permissions.
Both are required.
Interview Questions
What is Authentication?
Authentication verifies user identity.
What is Authorization?
Authorization verifies access permissions.
Which happens first?
Authentication always happens first.
Can Authorization work without Authentication?
No.
The system must know who the user is before checking permissions.
What is RBAC?
Role-Based Access Control.
Permissions are assigned through roles.
Difference between 401 and 403?
401:
Unauthenticated
403:
Authenticated but not authorized
Key Takeaways
- Authentication = Who are you?
- Authorization = What can you access?
- Authentication occurs before authorization.
- Spring Security provides both capabilities.
- RBAC is the most common authorization model.
- Method-level security improves protection.
- Production systems should use BCrypt, JWT, HTTPS, and MFA.
Next Article
➡️ Spring Security Architecture Deep Dive