So I tried to setup a Mvc where a user can submit a post to the server. The controller should call the service, which creates the new post entry. But I get a Nullpointer Exc
TL;DR Make your method public
instead of private
.
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_OWNER')")
@PostMapping(value = "/")
private ResponseEntity<?> savePost(@RequestBody Post post, Principal principal) { ... }
The problem is the fact that your method is private
and not public
combined with the @PreAuthorize
annotation.
The latter 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.
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) { ... }