首页 > 解决方案 > Spring Cloud Gateway - 设置自己的 RemoteTokenService

问题描述

我曾经在我的微服务环境中使用 Zuul 网关。我已经建立了自己的 OAUTH2 服务,它使用 Spring Security OAUTH2 库进行配置。在 Zuul 中,我发现了一个使用远程令牌服务的“技巧”,它指向我的内部 OAUTH2 服务。(下面的配置类)这就像一个魅力。

现在,我还必须将 Websockets 用于(网络)应用程序的另一部分。我发现 zuul不支持 websockets,我不知道应该如何升级到 zuul 2(我无法运行示例 OAUTH2 项目)。

所以我转向了新的 Spring Cloud Gateway,它应该支持 websockets。但是,现在我正在重新配置网关,我似乎无法弄清楚我应该如何配置它以使用我自己的资源服务器。

我使用/尝试的代码:

我原来的 RemoteTokenService 配置。这些值存储在 .env 文件中,uri 指向 zuul + /api/oauth/token

@Configuration
public class OAuth2ResourceServerConfigRemoteTokenService extends ResourceServerConfigurerAdapter {
    @Value("${security.oauth2.client.client-id}")
    private String clientId;
    @Value("${security.oauth2.client.client-secret}")
    private String clientSecret;
    @Value("${security.oauth2.token.uri}")
    private String tokenUrl;

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        // @formatter:off
        //TODO: Check what this exactly does (forces the need of a session?)
        http.cors().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .authorizeRequests().anyRequest().permitAll();
        // @formatter:on                
    }

    /**
     * Tells OAuth where the tokens should be validated.
     * In our case this is the authservice, which is routed through Zuul via the application.properties.
     */
    @Primary
    @Bean
    public RemoteTokenServices tokenServices() {
        final RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl(tokenUrl);
        tokenService.setClientId(clientId);
        tokenService.setClientSecret(clientSecret);
        return tokenService;
    }
}

我尝试在网关中使用此过滤器:

    @Bean
    SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
        return http
                .csrf().disable()
                .authorizeExchange()
                .pathMatchers("/oauth/**")
                .permitAll()
                .and()
                .authorizeExchange()
                .pathMatchers("/users/**")
                .authenticated()
                .anyExchange().permitAll()
                .and()
                .build();
    }

但是,当我尝试访问 /users/ 端点上的任何内容时,我得到一个 401;因为网关不知道它应该在哪里以及如何检查它获得的令牌。

请注意,我不使用 JWT 令牌,而是使用 UUID(我猜是默认配置)。因此,这.oauth2ResourceServer().jwt()似乎不适用。我似乎找不到任何有用的资料来说明.oauth2ResourceServer().bearerTokenConverter()应该做什么,文档没有提到它。

我希望云网关不要考虑它,只需向 authservice 发送请求以验证令牌。我试图复制上述RemoteTokenService配置,但这让我陷入了一个我无法摆脱的依赖地狱。

如何配置网关以使用我自己的授权服务器?

注意:这是一个学校项目,因此 100% 的生产安全性无关紧要。

标签: springspring-bootspring-securityspring-security-oauth2spring-cloud-gateway

解决方案


推荐阅读