0

我使用 Spring Cloud Gateway 作为 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();
}

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

4

1 回答 1

1

我创建了过滤器,用于将用户名和用户角色添加到下游服务请求的标头(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())
            }
}
于 2018-10-20T14:58:53.583 回答