采用不对称方法的OAuth2



我已经用springcloudoauth2实现了一个资源服务器和授权服务器。当我使用默认方法(不使用不对称或对称方法(实现OAuth应用程序时,默认令牌由授权服务器生成,当我必须与资源服务器和授权服务器通信时,可以在资源服务器配置文件中使用以下属性。

资源服务器.yml默认

security:
oauth2:
client:
client-id: web
client-secret: *****
resource:
token-info-uri: "http://localhost:9092/oauth/check_token"

当我使用非对称方法在授权服务器中使用私钥对令牌进行签名,并使用公钥在具有以下属性security:jwt:public-key: classpath:public.txt的资源服务器中验证令牌时,当我从资源服务器调用资源时,发生了以下未经授权的响应。

资源服务器.yml具有不对称

security:
jwt:
public-key: classpath:public.txt

API终点

http://localhost:9090/user?Authorization=bearer **********

响应

{
"error": "invalid_token",
"error_description": "Cannot convert access token to JSON"
}

请注意,当我在resource-server.yml中以非对称方式使用clienttoken-info-uri属性时,会出现以下错误。

Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a single bean, but 2 were found:
- tokenServices: defined by method 'tokenServices' in class path resource [com/benz/resource/api/config/ResourceServerConfiguration.class]
- remoteTokenServices: defined by method 'remoteTokenServices' in class path resource [org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfiguration$RemoteTokenServicesConfiguration$TokenInfoServicesConfiguration.

我必须澄清以下问题

  1. 在不使用token-info-uriclient属性的情况下,资源服务器如何识别特定的授权服务器?。

  2. 为什么会发生未经授权的错误(上面提到过(?

ResourceServerConfig类

@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Value("${security.jwt.public-key}")
private Resource publicKey;
private TokenStore tokenStore;

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore());
}
@Bean
public DefaultTokenServices tokenServices(TokenStore tokenStore)
{
DefaultTokenServices tokenServices=new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore);
return tokenServices;
}
@Bean
public TokenStore tokenStore() throws Exception
{
if(tokenStore==null)
tokenStore=new JwtTokenStore(tokenConverter());
return tokenStore;
}
private JwtAccessTokenConverter tokenConverter() throws Exception
{
JwtAccessTokenConverter converter=new JwtAccessTokenConverter();
converter.setVerifierKey(getPublicKeyAsString());
return converter;
}

private String getPublicKeyAsString() throws Exception
{
return IOUtils.toString(publicKey.getInputStream(),UTF_8);
}
}

的Github链接

资源服务器实现

授权服务器实现

如果您需要更多详细信息,请评论,然后我可以更新

我已经解决了这个问题。在我的例子中,tokenConverter方法是在创建JwtTokenStorebean实例时调用的。我通过添加@bean注释,改变了为JwtAccessTokenConverter单独创建bean实例的方法。在这种情况下,它是在没有任何中断的情况下工作的。

@Bean
public JwtAccessTokenConverter tokenConverter() throws Exception
{
JwtAccessTokenConverter converter=new JwtAccessTokenConverter();
converter.setVerifierKey(getPublicKeyAsString());
return converter;
}

最新更新