我正在尝试为spring项目配置OAuth2。我正在使用我的工作场所提供的共享UAA(oauth implementation from cloud foundry)实例(因此我没有尝试创建授权服务器,授权服务器与资源服务器是分开的)。前端是单页面应用程序,它使用隐式授权直接从授权服务器获取令牌。我有SPA设置,它在每个Web API调用微服务器上添加Authorization: Bearer <TOKEN>
标头。
我现在的问题是微服务。
我试图使用此共享授权服务器来验证微服务。我可能在这里有一个误解,购买我目前的理解是这些微服务扮演资源服务器的角色,因为它们托管SPA用来获取数据的端点。
所以我尝试配置像这样的微服务:
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated();
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey("-----BEGIN PUBLIC KEY-----<key omitted>-----END PUBLIC KEY-----");
return converter;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices());
}
}
现在每当我使用/api/**
点击Authorization: Bearer <TOKEN>
时,我都会收到403
错误:
{
"error": "access_denied",
"error_description": "Invalid token does not contain resource id (oauth2-resource)"
}
Principal
?我目前已将其设置为SPA所在的位置并发送令牌,我也有用于验证令牌签名的公钥。我还使用了jwt.io来测试令牌,并说“#34; Signature Verified&#34;。谢谢!
答案 0 :(得分:19)
Spring OAuth期待&#34; aud&#34; JWT令牌中的claim。该声明的值应与您为Spring应用指定的resourceId
值匹配(如果未指定,则默认为&#34; oauth2-resource&#34;)。
要解决您的问题,您需要:
1)登录您的共享UAA并确保它包含&#34; aud&#34;权利要求。
2)改变那个&#34; aud&#34;的价值。声称是&#34; oauth2-resource&#34;或者最好在你的Spring应用程序中更新resourceId
这个声明的值,如下所示:
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices());
resources.resourceId(value from the aud claim you got from UAA server);
}
答案 1 :(得分:1)
我添加了类似的问题。就我而言,我使用jdbc身份验证,而我的授权服务器和资源服务器是两个单独的API。
授权服务器
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.passwordEncoder(oauthClientPasswordEncoder);
}
/**
* Define the client details service. The client may be define either as in memory or in database.
* Here client with be fetch from the specify database
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
/**
* Define the authorization by providing authentificationManager
* And the token enhancement
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore())
.tokenEnhancer(getTokenEnhancer())
.authenticationManager(authenticationManager).userDetailsService(userDetailsService);
}
资源服务器
public class OAuth2ResourceServerConfig extends
ResourceServerConfigurerAdapter {
private TokenExtractor tokenExtractor = new BearerTokenExtractor();
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// We don't want to allow access to a resource with no token so clear
// the security context in case it is actually an OAuth2Authentication
if (tokenExtractor.extract(request) == null) {
SecurityContextHolder.clearContext();
}
filterChain.doFilter(request, response);
}
}, AbstractPreAuthenticatedProcessingFilter.class);
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated();
}
@Bean
public AccessTokenConverter accessTokenConverter() {
return new DefaultAccessTokenConverter();
}
@Bean
public RemoteTokenServices remoteTokenServices(final @Value("${auth.server.url}") String checkTokenUrl,
final @Value("${auth.resource.server.clientId}") String clientId,
final @Value("${auth.resource.server.clientsecret}") String clientSecret) {
final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
remoteTokenServices.setCheckTokenEndpointUrl(checkTokenUrl);
remoteTokenServices.setClientId(clientId);
remoteTokenServices.setClientSecret(clientSecret);
remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
return remoteTokenServices;
}
通过这种配置,我得到了
{
"error": "access_denied",
"error_description": "Invalid token does not contain resource id
(xxxxx)"
}
要解决此问题,我必须添加
private String resourceIds= "xxxxx". !! maked sure that this resourceids is store in oauth_client_details for the clientid I used to get the token
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(resourceIds).tokenStore(tokenStore());
}
答案 2 :(得分:1)
当我用spring实现oauth2.0时,我遇到了同样的问题,这是我发现的关于resourceid的发现。
Spring Security OAuth2体系结构分为授权服务器和资源服务器资源服务器。我们可以为每个资源服务器(一个微服务实例)设置一个ResourceID。当授权服务器向客户端授予授权时,您可以设置客户端可以访问的资源服务器资源服务。
在授权服务器中为客户端配置ResourceID的目的是限制客户端可以访问的资源服务。
要设置ResourceID引用以下链接, https://www.fatalerrors.org/a/resource-of-spring-security-oauth2_-id-configuration-and-verification.html