从 Spring 云网关到基础服务的凭证传播

Credentials propagation from Spring Cloud Gateway to underlying service

我使用 Spring 云网关作为 UI 网关。安全配置:

@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
    return http.httpBasic().and()
            .formLogin().loginPage("/login")
            .and()
            .authorizeExchange().anyExchange().permitAll()
            .and()
            .build();
}

如何将当前用户凭据(用户名和角色)传播到基础服务?我需要在路由配置中添加一些自定义过滤器吗:

@Bean
RouteLocator routeLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("some-ui", r -> r.path("/some-ui-context-path/**")
                    .uri("lb://some-ui"))
            .build();
}

?是否有用于此目的的标准组件?

我创建了用于向 headers 下游服务请求(Kotlin 代码)添加用户名和用户角色的过滤器:

@Component
class AddCredentialsGlobalFilter : GlobalFilter {

    private val usernameHeader = "logged-in-user"
    private val rolesHeader = "logged-in-user-roles"

    override fun filter(exchange: ServerWebExchange, chain: GatewayFilterChain) = exchange.getPrincipal<Principal>()
            .flatMap { p ->
                val request = exchange.request.mutate()
                        .header(usernameHeader, p.name)
                        .header(rolesHeader, (p as Authentication).authorities?.joinToString(";") ?: "")
                        .build()
                chain.filter(exchange.mutate().request(request).build())
            }
}