How to set up a proxy with authentication in Feign

Feign Proxy support (with authentication)

Some companies may have to go through a proxy that requires authentication when connecting to the Internet. I would like to explain how to set proxy when calling an API published on the Internet using the API client Feign in such an environment.

Feign delegates the process of issuing an HTTP request to another library. In other words, you only have to support proxy of the library to be used.

This time, I changed Feign's Sample to get contributor of specified repository of GitHub explained on GitHub page to support proxy. to watch.

For the explanation of Feign, please refer to" Feign that implements API client only with interface is very convenient! ".

GitHubDemo.java


package com.example.feign.demo.github;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;
import java.util.concurrent.TimeUnit;

import feign.Feign;
import feign.jackson.JacksonDecoder;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

/**
 * modify Feign example(https://github.com/OpenFeign/feign) to corresponded proxy
 */
public class GitHubDemo {

    public static void main(String[] args) {

        // create instance of okhttp3.OkHttpClient corresponded proxy 
        OkHttpClient client = createOkHttpClientCorrespondedProxy("127.0.0.1",
                8080, "userId", "pass");

        // feign use proxy with authentication
        GitHub github = Feign.builder()
                // set instance of feign.Client.OkHttpClient
                .client(new feign.okhttp.OkHttpClient(client))
                // use Jackson
                .decoder(new JacksonDecoder())
                .target(GitHub.class, "https://api.github.com");

        // call api [GET /repos/{owner}/{repo}/contributors]
        List<Contributor> contributors = github.contributors("OpenFeign",
                "feign");
        for (Contributor contributor : contributors) {
            System.out.println(
                    contributor.login + " (" + contributor.contributions + ")");
        }
    }

    /**
     * create instance of okhttp3.OkHttpClient corresponded proxy
     * @param proxyHost proxy's host url or ipAddress
     * @param proxyPort proxy's port number
     * @param userId userId of proxy's authentication
     * @param pass pass of proxy's authentication
     * @return instance of okhttp3.OkHttpClient
     */
    private static OkHttpClient createOkHttpClientCorrespondedProxy(
            String proxyHost, int proxyPort, String userId, String pass) {

        // okhttp3.Authenticator : correct
        // java.net.Authenticator : incorrect
        Authenticator proxyAuthenticator = new Authenticator() {
            @Override
            public Request authenticate(Route route,
                    Response response) throws IOException {
                String credential = Credentials.basic(userId, pass);
                return response.request().newBuilder()
                        .header("Proxy-Authorization", credential).build();
            }
        };

        // okhttp3.OkHttpClient : correct
        // feign.Client.OkHttpClient : incorrect
        return new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .proxy(new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyHost, proxyPort)))
                .proxyAuthenticator(proxyAuthenticator).build();
    }
}

The points to note are shown below.

(reference) https://stackoverflow.com/questions/35554380/okhttpclient-proxy-authentication-how-to

Recommended Posts

How to set up a proxy with authentication in Feign
[How to insert a video in haml with Rails]
[Rails 6] How to set a background image in Rails [CSS]
How to set Lombok in Eclipse
Summary of how to use the proxy set in IE when connecting with Java
How to make a jar file with no dependencies in Maven
How to run a job with docker login in AWS batch
How to rename a model with foreign key constraints in Rails
[Note] How to restart the Windows container set up with docker-compose
How to insert a video in Rails
How to set up and use kapt
How to achieve file download with Feign
Steps to set a favicon in Rails
How to set JAVA_HOME with Maven appassembler-maven-plugin
How to achieve file upload with Feign
[Personal memo] How to interact with a random number generator in Java
Minimal steps to set up a Ruby environment with rbenv on Ubuntu 20.04
How to pass a proxy when throwing REST over SSL in Java
How to SSH into Ubuntu from a terminal with public key authentication
How to start a Docker container with a volume mounted in a batch file
Set up a Java GUI in a separate thread to keep the main
How to display a web page in Java
How to run a djUnit task in Ant
How to add a classpath in Spring Boot
How to create a theme in Liferay 7 / DXP
How to set up and operate jEnv (Mac)
How to implement a like feature in Rails
How to easily create a pull-down in Rails
How to set up JavaED Full Edition (pleiades)
How to write test code with Basic authentication
Set up a webhook in Shopify's custom app
Set up a CentOS virtual server with Vagrant
How to automatically generate a constructor in Eclipse
How to get the ID of a user authenticated with Firebase in Swift
Introduced # 10 devise_token_auth to build a bulletin board API with authentication authorization in Rails 6
Introducing # 15 pundit to build a bulletin board API with authentication authorization in Rails 6
How to store data simultaneously in a model associated with a nested form (Rails 6.0.0)
How to set up computer vision for tracking images and videos with TrackingJs
How to embed JavaScript variables in HTML with Thymeleaf
How to implement UICollectionView in Swift with code only
How to clear all data in a particular table
How to call functions in bulk with Java reflection
How to create a Java environment in just 3 seconds
How to set the display time to Japan time in Rails
How to implement a like feature in Ajax in Rails
How to switch Tomcat context.xml with WTP in Eclipse
How to delete a new_record object built with Rails
[Android / Java] Set up a button to return to Fragment
How to use Z3 library in Scala with Eclipse
How to create a Spring Boot project in IntelliJ
How to manually generate a JWT with Rails Knock
How to create a data URI (base64) in Java
How to display a browser preview in VS Code
Steps to set up a VNC server on CentOS 8.3
How to delete untagged images in bulk with Docker
How to write a date comparison search in Rails
How to store Rakuten API data in a table
How to mock a super method call in PowerMock
How to use JDD library in Scala with Eclipse
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java