【问题标题】:How to call different method based on oauth authority如何根据 oauth 权限调用不同的方法
【发布时间】:2018-09-27 07:43:36
【问题描述】:

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

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

【问题讨论】:

  • 只编写了一个方法,并根据用户的权限将调用委托给另一个方法。只是一个 if 语句。
  • 是的。我找不到任何解决方案,而且我已经在这样做了。不过谢谢! :)

标签: java spring spring-security spring-oauth2


【解决方案1】:

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

您可以在控制器中获取对 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.";
    }

【讨论】:

  • 我做过类似的解决方案。但是我得到了我作为参数传递的 org.springframework.security.core.Authentication 的权限。谢谢。
猜你喜欢
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
相关资源
最近更新 更多