记录一下使用SpringSecurity的OAuth2时遇到的错误

问题描述

在结合SpringCloud组件Gateway和SpringSecurity5做OAuth2登录时,从登录界面跳转时会发生authorization_request_not_found的错误,但重新输入地址访问后可以看到登录是成功的。由于不影响使用,我一直拖着没解决这个问题,直到最近有时间静下心来看看。

各种翻github后,从结论来说,这个问题是由于Gateway内置的WebClient和SpringSecurity内置的WebClient冲突导致的,这个SpringSecurity的Webclient的bean貌似在注入的过程中被Gateway的给替换掉了。

解决(替换回去)

根据官方给的解决方案
写一个WebClient的bean把之前的再替换掉

@Configuration
public class WebClientConfig {

    @Value("${server.port}") Integer port;

    @Bean
    WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
                new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        oauth.setDefaultOAuth2AuthorizedClient(true);
        return WebClient.builder()
                .baseUrl("127.0.0.1:"+this.port)
                .filter(oauth)
                .build();
    }

    @Bean
    ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
            ReactiveClientRegistrationRepository clientRegistrationRepository,
            ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

        ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
                ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
                        .authorizationCode()
                        .refreshToken()
                        .clientCredentials()
                        .password()
                        .build();
        DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager =
                new DefaultReactiveOAuth2AuthorizedClientManager(
                        clientRegistrationRepository, authorizedClientRepository);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

        return authorizedClientManager;
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐