我使用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();
}
?是否有用于此目的的标准组件?
答案 0 :(得分:0)
我创建了过滤器,用于将用户名和用户角色添加到下游服务请求的标头(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())
}
}