spring-bootrestinterceptorfeignopenfeign

How to send/set basic authorization i.e user and password to every request in openFeign client in spring boot with help of interceptor


How to send or set basic authorization, i.e., user and password, to every request in the openFeign client in Spring Boot with help for the interceptor As I am trying to implement an openFeign client for an external service in spring boot, which always expects basic authentication in its request header, i.e., user ID and password, I can send fixed values like the ones below with interceptor, but it is always fix values that picked from properties:

@Configuration
@EnableFeignClients(basePackages = {"com.abc.xyz.feign"})
public class CsdClientConfig {
    @Value("${cds-service-provider.userId}")
    private String userId;
    @Value("${cds-service-provider.password}")
    private String password;

    @Bean
    BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor(userId,password);
    }

I want to receive this auth info from a feign api caller for every api call and set it to header of service to access resources .i.e from postman

How can I accept it from the request header and pass it to feign client for further processing?

[! [enter image description here] 1]1


Solution

  • I found the way as below: So we can use RequestInterceptor to inject headers from every request to the feign client on every request.

    @Component
    @AllArgsConstructor
    public class FeignClientInterceptor implements RequestInterceptor {
        final HttpServletRequest request;
        @Override
        public void apply(RequestTemplate requestTemplate) {
            String reqAuthInput= request.getHeader("authorization");
            if (reqAuthInput!= null) {
                requestTemplate.header("authorization",reqAuthInput);
            }
        }
    }