在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");
}
}