Spring Cloud Alibaba微服务实战十四 - SpringCloud Gateway集成Oauth2.0
    		       		warning:
    		            这篇文章距离上次修改已过421天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Cloud Alibaba微服务实战系列中,我们已经完成了与OAuth2.0整合的基本框架。以下是一个简化版的Spring Cloud Gateway与OAuth2.0整合的核心配置代码:
@Configuration
@EnableConfigurationProperties(ResourceServerProperties.class)
public class ResourceServerConfig {
 
    @Autowired
    private ResourceServerProperties resource;
 
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt();
        return http.build();
    }
}
 
@Configuration
public class GatewayConfig {
 
    @Autowired
    private AuthenticationManager authenticationManager;
 
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("path_route", r -> r.path("/api/resource/**")
                    .filters(f -> f.requestRateLimiter(config -> config.setKeyResolver(getPrincipalNameKeyResolver())))
                    .uri("lb://resource-service")
                    .order(0)
                    .id("path_route"))
            .build();
    }
 
    private KeyResolver getPrincipalNameKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    }
}
 
@Configuration
public class SecurityConfig {
 
    @Bean
    public ReactiveJwtDecoder jwtDecoder() {
        return JwtDecoders.fromIssuerLocation(this.resource.getJwt().getIssuerUri());
    }
}在这个配置中,我们定义了ResourceServerConfig来设置资源服务器的安全过滤链,它使用了OAuth2资源服务器支持和JWT(JSON Web Token)支持。GatewayConfig定义了网关路由的配置,它包括了一个路由,用于将对/api/resource/路径下的请求转发到后端服务,并使用了请求限流功能。SecurityConfig定义了JWT解码器的配置。
请注意,这个代码示例假定你已经有了一个有效的OAuth2.0提供者和相关的配置属性。在实际应用中,你需要根据自己的配置调整ResourceServerProperties、JWT的颁发者URI和请求限流的KeyResolver。
评论已关闭