【问题标题】:Spring OAuth2 - Authorize URLs with Additional InformationSpring OAuth2 - 使用附加信息授权 URL
【发布时间】:2018-09-20 00:29:47
【问题描述】:

如果我们设置了授权权限,Spring security 允许我们使用hasAnyAuthority()hasAnyRole()hasRole() 授权 URL。如果我创建了一个自定义令牌增强器,我可以在我的令牌中添加附加信息,有没有办法使用附加信息进行授权?

自定义令牌增强器:

public final class CustomTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(
            OAuth2AccessToken accessToken,
            OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put("company", "authorizeAPIsWithCompany");
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}

是否可以根据上述附加信息键、值授权 API?如果没有,我应该如何处理这个想法?

例如:

@Override
public void configure(HttpSecurity http) throws Exception {
     http
            .authorizeRequests()
  .antMatchers("/authorizedURL").hasCompany("authorizeAPIsWithCompany")
  .....

}

【问题讨论】:

    标签: spring spring-boot spring-security spring-security-oauth2 spring-oauth2


    【解决方案1】:

    我认为您可以在不使用其他信息的情况下做您想做的事。 OAuth 协议不需要其他信息。它只是用于存储描述性信息。您应该能够通过客户的范围、权限和授权类型以及用户的权限(角色)来实现您想要的。您可以查看 Oauth2 规范 (https://www.rfc-editor.org/rfc/rfc6749) 了解更多信息。

    你也可以有不同的安全策略,比如 MethodSecurityConfig:

    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }
    }
    
    @PreAuthorize("hasRole('ADMIN') OR #oauth2.clientHasRole('AUTHORIZED-MERCHANT')")
    @GetMapping(value = "authorized-url")
    public ResponseEntity<List<Order>> getOrders() {
        return ResponseEntity.ok(orderService.getOrders());
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-11
      • 2016-07-08
      • 2022-10-20
      • 2015-09-05
      • 2022-11-14
      • 2023-04-05
      • 2015-03-31
      • 2014-05-10
      • 2013-12-01
      相关资源
      最近更新 更多