Performance: Custom permission evaluator
This affects the speed of authorization checks during user interactions, impacting input responsiveness and overall user experience.
Jump into concepts and practice - no test required
public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {
// Use cached permissions stored in Authentication object
Set<String> permissions = auth.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toSet());
return permissions.contains(permission);
}public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {
// Heavy database call on every permission check
User user = userRepository.findByUsername(auth.getName());
return user.getPermissions().contains(permission);
}| Pattern | DB Calls | Permission Checks | Latency Impact | Verdict |
|---|---|---|---|---|
| Direct DB call per check | Multiple per request | High | 50-100ms delay per check | [X] Bad |
| Cached permissions in Authentication | None after login | Low | Under 1ms per check | [OK] Good |
Custom PermissionEvaluator in Spring Boot security?PermissionEvaluator to check permissions based on a target domain object?hasPermission(Authentication authentication, Object targetDomainObject, Object permission) is used to check permissions on a domain object.public boolean hasPermission(Authentication auth, Object target, Object perm) {
if (auth == null || target == null || !(perm instanceof String)) {
return false;
}
String permission = (String) perm;
User user = (User) auth.getPrincipal();
return user.getRoles().contains(permission);
}auth is null?auth is null and returns false immediately if so.auth == null triggers return false, no further code runs and no exception occurs.public boolean hasPermission(Authentication auth, Object target, Object perm) {
String permission = (String) perm;
User user = (User) auth.getPrincipal();
return user.getRoles().contains(permission);
}auth, perm, or auth.getPrincipal() are null before casting or calling methods.hasPermission?