2016-08-08 29 views
1

在Spring中是否存在基于oauth2范围的基于注释或DI的实现资源域级别过滤的方法?Spring Boot - OAuth2 - 范围限制现场级别的资源

我们有一个基于spring启动的资源服务器,它具有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"); 
    } 
} 

回答