【发布时间】:2017-10-07 03:38:21
【问题描述】:
我正在尝试使用 ResourceServerConfigurerAdapter(使用 Oauth2 client_credentials)访问受 Spring Security 保护的 Web 服务
以下是安全配置
//Micoservice 1
@Configuration
@EnableResourceServer
class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private Environment env;
@Autowired
private DummyUserFilter dummyUserFilter;
@Override
public void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(dummyUserFilter, LogoutFilter.class)
.formLogin().disable()
.httpBasic().disable()
.csrf().disable()
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/js/**", "/webjars/**").permitAll()
.anyRequest()
.authenticated();
}
}
此应用程序(微服务 1)将由另一个应用程序(微服务 2)使用Oauth2RestTemplate 访问。以下是Oauth2RestTemplate 配置。
//MicroService 2
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
resourceDetails.setAccessTokenUri("https://<UAA>/oauth/token");
resourceDetails.setClientId("#####");
resourceDetails.setClientSecret("#####");
resourceDetails.setGrantType("client_credentials");
resourceDetails.setTokenName("access_token");
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);
return restTemplate;
}
}
Microservice 2 有各种 Web 服务,它们使用 RestTemplate 访问受保护的 Microservice 1 的 Web 服务。
这总是会导致以下异常
需要验证才能获取访问令牌(不允许匿名)
我搜索了这个错误,发现是在AccessTokenProviderChain中抛出的
这里是来自 github 的相关代码链接
if (auth instanceof AnonymousAuthenticationToken) {
if (!resource.isClientOnly()) {
throw new InsufficientAuthenticationException(
"Authentication is required to obtain an access token (anonymous not allowed)");
}
}
它似乎不允许匿名用户访问 Oauth2 令牌。
我无意使用 Oauth2 保护客户端应用程序(微服务 2),我必须将 client_credentials 用于预配置的 Oauth2RestTemplate。
如何阻止 Spring 阻止匿名用户访问令牌?
我已经尝试在匿名用户的情况下使用虚拟身份验证填充SecurityContextHolder,但没有成功。即使我确实成功了,这似乎也是一种 hack。
【问题讨论】:
-
现在我已经通过将
Oauth2RestTemplate的创建完全与 Spring 分开来解决它。如果我为Oauth2RestTemplate创建一个bean 或尝试自动装配它,Spring 会检测并尝试干扰它。所以我为Oauth2RestTemplate创建了我自己的单例类,它与 Spring 无关,现在它可以工作了。不过我期待一个真正的答案。 -
您是否尝试过使用
OAuth2RestTemplate restTemplate定义OAuth2RestTemplate类型的restTemplatebean 而不是RestTemplate和@autowireing?另一方面,如果您使用的是ClientCredentialResourceDetails,则抛出InsufficientAuthenticationException是没有意义的,因为它显然会为isClientOnly()github.com/spring-projects/spring-security-oauth/blob/master/… 返回true。其他 Bean 有机会吗? -
是的,我使用了 Oauth2RestTemplate,正如您在我在问题中发布的代码中看到的那样,它会引发相同的错误。我不认为还有另一个 bean,现在它通过创建自定义单例来工作。
标签: java spring spring-boot spring-security spring-oauth2