github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/java/libraries/retrofit2/auth/HttpBasicAuth.mustache (about)

     1  package {{invokerPackage}}.auth;
     2  
     3  import java.io.IOException;
     4  
     5  import okhttp3.Interceptor;
     6  import okhttp3.OkHttpClient;
     7  import okhttp3.Request;
     8  import okhttp3.Response;
     9  import okhttp3.Credentials;
    10  
    11  public class HttpBasicAuth implements Interceptor {
    12  
    13      private String username;
    14      private String password;
    15      
    16      public String getUsername() {
    17          return username;
    18      }
    19  
    20      public void setUsername(String username) {
    21          this.username = username;
    22      }
    23  
    24      public String getPassword() {
    25          return password;
    26      }
    27  
    28      public void setPassword(String password) {
    29          this.password = password;
    30      }
    31  
    32      public void setCredentials(String username, String password) {
    33          this.username = username;
    34          this.password = password;
    35      }
    36  
    37      @Override
    38      public Response intercept(Chain chain) throws IOException {
    39          Request request = chain.request();
    40  
    41          // If the request already have an authorization (eg. Basic auth), do nothing
    42          if (request.header("Authorization") == null) {
    43              String credentials = Credentials.basic(username, password);
    44              request = request.newBuilder()
    45                      .addHeader("Authorization", credentials)
    46                      .build();
    47          }
    48          return chain.proceed(request);
    49      }
    50  }