Spring Cloud Gateway Server MVC add header from authentication for all requests

220 Views Asked by At

I found a solution for spring reactive cloud gateway, but how to do it in spring cloud gateway server mvc without webflux? Spring cloud gateway add header from authentication Spring Cloud Gateway inject header

I tried to do this through implementing HttpServletRequestWrapper in my gateway as stated here Adding an HTTP Header to the request in a servlet filter, but I see that the request coming to another microservice is missing my headers.

UPD: the implementation option specified here also worked Adding an HTTP Header to the request in a servlet filter

1

There are 1 best solutions below

1
Niyaz Khannanov On
    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsAddReqHeader(
            AuthenticationHeadersFilter authenticationHeadersFilter,
            GatewayConfig gatewayConfig
    ) {
        ServiceProperties serviceProperties = gatewayConfig.getServices()
                .getOrDefault(CONTENT_SERVICE_NAME, new ServiceProperties());
        return route("content_service_content")
                .PUT("/v1/content/user", http(serviceProperties.getUri()))
                .before(authenticationHeadersFilter.addRequestHeader())
                .build();
    };

    @Component
    public class AuthenticationHeadersFilter {
    private final AuthClient authServiceClient;

    public AuthenticationHeadersFilter(AuthClient authServiceClient) {
        this.authServiceClient = authServiceClient;
    }

    public Function<ServerRequest, ServerRequest> addRequestHeader() {
        return request -> {
            String token = request.servletRequest().getHeader(HttpHeaders.AUTHORIZATION);
            if (StringUtils.isNotBlank(token) && token.startsWith("Bearer ")) {
                JwtResponse validUser = authServiceClient.getValidUser(token.substring(7));
                Consumer<HttpHeaders> headers = httpHeaders -> {
                    httpHeaders.add(Headers.EMAIL, validUser.getEmail());
                    httpHeaders.add(Headers.USER_ID, validUser.getId().toString());
                    httpHeaders.add(Headers.ROLES, String.join(",", validUser.getRoles().stream().map(Enum::name).toList()));
                    httpHeaders.add(Headers.LAST_NAME, validUser.getLastName());
                };
                return ServerRequest.from(request)
                        .headers(headers)
                        .build();
            } else {
                throw new ResponseCodeException(new BadRequestError("Invalid token"));
            }
        };
    }

}