0

I want my resource to be like this. Same method mapping but each will be called based on the authority of who sent the request. Any solution for this?

@RestController
@RequestMapping("/test")
public class TestResource {

    @GetMapping
    @PreAuthorize("hasAuthority('COMMITTEE')")
    public String testForCommittee() {
        return "This is a test. Custom result for committee.";
    }

    @GetMapping
    @PreAuthorize("hasAuthority('ADMIN')")
    public String testForAdmin() {
        return "This is a test. Custom result for admin.";
    }
}

1 Answers1

0

May be not the perfect solution, but this can be a good workaroud for you.

You can get a reference to the Principal within your controller. You can either use generic java.security.Principal. I used org.springframework.security.oauth2.provider.OAuth2Authentication since I am using OAuth.

@GetMapping

    public String testForCommittee(org.springframework.security.oauth2.provider.OAuth2Authentication principal) {
        Collection<GrantedAuthority> authorities = principal.getAuthorities();
        //since you have all the authorities you can switch method call depending on the authorities

        if(authorities.contains(new SimpleGrantedAuthority("COMMITTEE"))){
          //user has COMMITEE authority.
        }else if{
          // check more
         }
        return "This is a test. Custom result for committee.";
    }
Udara S.S Liyanage
  • 6,189
  • 9
  • 33
  • 34
  • I've done a similar solution. But I get the authorities on org.springframework.security.core.Authentication that I passed as a parameter. Thanks. – Rome Joseph Santos Apr 30 '18 at 05:49