如何根据oauth权限调用不同的方法

How to call different method based on oauth authority

我希望我的资源是这样的。相同的方法映射,但将根据发送请求的人的权限调用每个方法。有什么解决办法吗?

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

可能不是完美的解决方案,但这对您来说可能是一个很好的解决方法。

您可以在控制器中获取对 Principal 的引用。您可以使用通用 java.security.Principal。我使用 org.springframework.security.oauth2.provider.OAuth2Authentication 因为我使用的是 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.";
    }