@PreAuthorize with use Spring Expression Language (SpEL) and service method call

public interface EventRepository extends JpaRepository<Event, Long> {
 
	@PreAuthorize("@securityService.canSave(#event,principal)")
	Event save(@Param("event") Event event);
 
	@PreAuthorize("@securityService.canSave2(#event)")
	Event save2(@Param("event") Event event); 
}
 
@Service("securityService")
public class SecurityService {
 
	public boolean canSave(Event event, UserDetails principal) {
		// some logic here
	}
 
	public boolean canSave2(Event event) {
 
		// get principal from Security Context
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
 
		// some logic here
	}
 
}

Leave a Reply

Your email address will not be published. Required fields are marked *