This tutorial is going to illustrate how to do basic authentication with Open Feign, a java to http client binder powered by OpenFiegn.

1. Overview

In general, we will use the BasicAuthRequestInterceptor class, which is an interceptor that adds the request header needed to use HTTP basic authentication, for basic authentication purposes.

In this tutorial, let’s assume that we will consume a REST API that requires basic authentication on the https://httpbin.org/, a HTTP Client Testing Service. The REST API which returns the current authenticated user and status, can be described as below:

Responses: application/json

Example:

STATUS 200 if get resource successfully.
STATUS 401 if not authorized.

2. The source code

In this tutorial, we will use the Feign version: 8.18.0. The Maven dependencies are as below:

The source code can be found on Github or you can download it via the link:java-examples.zip

3. Basic Authentication with Open Feign

3.1. Define a Proxy Interface at the client side

Firstly, we need to define a proxy interface which contains all methods targeted with the REST API. Let’s see how the interface is defined as below:

For more detail, you can refer to my recent post about implementing Java REST client using Feign.

As for the response, we also need to define a class to bind with it. Let’s see how it is defined:

3.2. Invoke methods on the Proxy

Now we will invoke the method defined on the Proxy Interface. Note that the method require basic authentication. Let’s see an example code:

Here are some essential points:

  • We create a instance of the BasicAuthRequestInterceptor with default username and password for basic authentication with the REST API and set it as a request interceptor of the Feign targeted http apis.
  • We use JacksonEncoder to convert the response into our AuthStatus object.

3.3. Verify

Let’s write a piece of unit test for the method:

Running the test will give the Green color.

4. Conclusion

The tutorial has just shown you how to do basic authentication with Open Feign by using the BasicAuthRequestInterceptor class as a request interceptor. Beside, there are other approaches to do basic authentication and we will get to know in next posts. Here are other related articles:

Java REST Client Using Netflix Feign

File Uploading with Open Feign

Java REST Client Example

 

 

 

0 0 vote
Article Rating