Authentication (Xác thực): "Bạn là ai?" — verify identity.
Authorization (Phân quyền): "Bạn được phép làm gì?" — check permission.
Authentication xảy ra trước Authorization.
Spring Security Authentication:
@Service
class UserService implements UserDetailsService {
public UserDetails loadUserByUsername(String email) {
User u = userRepo.findByEmail(email).orElseThrow();
return new org.springframework.security.core.userdetails.User(
u.getEmail(), u.getPasswordHash(),
List.of(new SimpleGrantedAuthority("ROLE_" + u.getRole()))
);
}
}Spring Security Authorization:
http.authorizeHttpRequests(a -> a
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()
);Method-level authorization:
@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
User getUser(Long userId) { ... }Sau authentication → SecurityContextHolder giữ Authentication object (user info, roles) cho thread hiện tại.
Authentication: "Who are you?" — verifying identity.
Authorization: "What are you allowed to do?" — checking permissions.
Authentication always happens before authorization.
Spring Security Authentication:
@Service
class UserService implements UserDetailsService {
public UserDetails loadUserByUsername(String email) {
User u = userRepo.findByEmail(email).orElseThrow();
return new org.springframework.security.core.userdetails.User(
u.getEmail(), u.getPasswordHash(),
List.of(new SimpleGrantedAuthority("ROLE_" + u.getRole()))
);
}
}Spring Security Authorization:
http.authorizeHttpRequests(a -> a
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()
);Method-level authorization:
@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
User getUser(Long userId) { ... }After authentication → SecurityContextHolder holds the Authentication object (user info, roles) for the current thread.