Spring Boot - OAuth2 - 现场级限制资源

时间:2016-08-08 20:14:56

标签: spring-security-oauth2

是否有基于注释或基于DI的方法在Spring中基于oauth2作用域实现资源字段级过滤?

我们有一个基于Spring Boot的资源服务器,它具有oauth2作用域保护端点。这适用于范围保护端点,但我们希望能够根据范围从我们公开的资源中过滤敏感信息。例如。我只想在客户端范围允许的情况下暴露一个人的SSN的最后4个。

到目前为止,我发现在资源服务器上执行此操作的唯一方法是:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
OAuth2SecurityExpressionMethods expressionMethods = new OAuth2SecurityExpressionMethods(authentication);

boolean hasScope = expressionMethods.hasScope("xyz.read");

if(hasScope) {
  resource.setSsn(entity.getSsn());   
}

因此,当范围“xyz.read”不存在时,资源将如下所示:

{
  "name": "blah"
}

但是当存在范围“xyz.read”时,资源将如下所示:

{
  "name": "blah",
  "ssn": "123-45-2347"
}

每次我们想要检查范围时,必须从安全上下文持有者伸出并获取身份验证对象并构建新的OAuth2SecurityExpressionMethods似乎我们错过了一些东西。但是,由于这是一个“纯粹的”OAuth2资源服务器,我们还没有找到更好的方法来实现这一目标。

这就是我们的资源服务器配置的样子(它确实可以正常工作):

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/health").permitAll()
            .antMatchers("/info").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/**").access("#oauth2.hasScope('xyz.read')");
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("resource-id");
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用@JsonView批注,其中视图名称反映了身份验证或访问级别。看看本教程:http://www.baeldung.com/jackson-json-view-annotation

目标:当对象被序列化时,视图将指示应显示/序列化哪些字段。

相关问题