0

I have a code block like below. For each method, I call action authentication. Is it possible to do with annotation or other thing effectively?

@GetMapping
public ResponseEntity getAction(@PrincipalUser user, Long actionId)
{
   repository.checkUserForAction(user.getId(), actionId);
   implement actions...
   return service call;
}
@PostMapping
public ResponseEntity addAction(@PrincipalUser user)
{
   repository.checkUserForAction(user.getId());
   implement actions...
   return service call;
}
@DeleteMapping
public ResponseEntity addAction(@PrincipalUser user, Long actionId)
{
   repository.checkUserForAction(user.getId(), actionId);
   implement actions... 
   return service call;
}

Actually, in here my other problem is that I call repository method each time and I know this is not an effective way.

Sha
  • 921
  • 17
  • 46

1 Answers1

2

You could use Spring Security and @PreAuthorize annotation.

Example:

@PreAuthorize("@authorizationService.check(#actionId)")
@DeleteMapping
public ResponseEntity performAction(Long actionId) {
implement actions...
}

And encapsulate authorization logic inside authorizationService, moreover authorizationService must be a bean and @EnableGlobalMethodSecurity(prePostEnabled = true) must be set.

Dominik
  • 353
  • 1
  • 5
  • Thanks @Dominik, this will be helpful for me. https://stackoverflow.com/questions/18470479/call-a-private-method-in-spring-preauthorize – Sha Jun 01 '19 at 09:11
  • But I try to find a solution on class level because the line of code won't be changed with method level solution. – Sha Jun 01 '19 at 09:14