Correctness34 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki

@PreAuthorize should not combine with public method

Description

@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_OWNER')")
@PostMapping(value = "/")
private ResponseEntity<?> savePost(@RequestBody Post post, Principal principal) { ... }

@PreAuthorize combined with public method will lead to a proxy being created to apply AOP and add the security interceptor. However a proxy will have all fields set to null as it only acts as a wrapper for the real instance hidden inside the proxy.

Theory

Solution

However your method is private and can thus not be overriden by another method and thus it will be called on the proxy, which has all the fields set to null. Making the method public will allow the proxy to override the method, add the security interceptor and eventually call the method on the object hidden inside the proxy.

@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_OWNER')")
@PostMapping(value = "/")
public ResponseEntity<?> savePost(@RequestBody Post post, Principal principal) { ... }

Link

https://stackoverflow.com/questions/56136841/spring-service-nullpointer-exception?noredirect=1&lq=1