Search code examples
javaspringspring-securityspring-oauth2

How to call different method based on oauth authority


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.";
    }
}

Solution

  • 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.";
        }