How to consume basic-authentication protected Restful web service via feign client

Zhuo YING picture Zhuo YING · Sep 21, 2016 · Viewed 19.3k times · Source

Thank you for your time. To make it simple, I created a example service like below:

@RestController
@RequestMapping("/")
public class ComputeController {

    @GetMapping("/add")
    public int add(@RequestParam("left") int left, @RequestParam("right") int right) {
        return left + right;
    }
}

To protected this url, I config spring-security like this:

management.security.enabled=true
security.user.name=admin
security.user.password=admin

When I startup this service and access like this:

GET /add?left=100&right=11 HTTP/1.1
Authorization: ***** Hidden credentials *****
Host: localhost:7777
Connection: close

Everythis is going fine.

In other node, I created a "service-comsumer" by netflix feign. It's a Java Interface.

@FeignClient(name = "API-GATEWAY", path = "/compute-service", fallback = ComputeServiceCircuitBreaker.class)
public interface ComputeServiceClient {

    @RequestMapping(path = "/add", method = RequestMethod.GET)
    public Integer add(@RequestParam("left") Integer left, @RequestParam("right") Integer right);
}

But I DO NOT know how to config the request header "Authorization".

Any idea? Thanks again.

Answer

Juan Pablo G picture Juan Pablo G · Dec 13, 2016

you need to create a FeignClient Configuration class, for example

import feign.auth.BasicAuthRequestInterceptor;

@Configuration
public class FeignClientConfiguration {
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
         return new BasicAuthRequestInterceptor("admin", "admin");
    }
}

then in your @FeignClient annotation use this configuration file

@FeignClient(name="service",configuration = FeignClientConfiguration.class)

go ahead and try it, hope it helps

Thanks to Ryan Baxter for his correction