Performance: Role-based access control
This affects page load speed indirectly by controlling which UI elements and API endpoints are accessible, impacting rendering and interaction responsiveness.
Jump into concepts and practice - no test required
public boolean hasAccess(User user, String role) {
Set<String> roles = user.getRoles().stream()
.map(Role::getName)
.collect(Collectors.toSet());
return roles.contains(role);
}
// Cache roles per session or use Spring Security's built-in role managementpublic boolean hasAccess(User user, String role) {
for (Role r : user.getRoles()) {
if (r.getName().equals(role)) {
return true;
}
}
return false;
}
// Called repeatedly in UI rendering and API filters without caching| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated role checks without caching | Multiple redundant checks | Multiple reflows if UI changes per check | High due to conditional rendering | [X] Bad |
| Cached role checks with Set lookup | Minimal, single check per render | Single reflow if UI changes | Low paint cost | [OK] Good |
@PreAuthorize("hasRole('ADMIN')"), what will happen if a user with role USER tries to access this method?@PreAuthorize("hasRole('ADMIN')")
public String adminPage() {
return "Welcome Admin";
}@PreAuthorize expression correctly enforces this?