Roman Q
Roman Q

Reputation: 287

Credentials propagation from Spring Cloud Gateway to underlying service

I use Spring Cloud Gateway as UI gateway. Security config:

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

How I can propagate current user credentials (username and roles) to underlying services? Do I need add some custom filters to routes config:

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

? Is there a standard component for this purpose?

Upvotes: 0

Views: 2161

Answers (1)

Roman Q
Roman Q

Reputation: 287

I created filter for adding username and user roles to headers of downstream services request (code on 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())
            }
}

Upvotes: 1

Related Questions