001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.ws.client;
015
016import java.nio.charset.Charset;
017import java.nio.charset.StandardCharsets;
018import java.util.Base64;
019
020import feign.RequestInterceptor;
021import feign.RequestTemplate;
022
023/**
024 * A small request interceptor for a single, fixed user. Request Interceptor adding HTTP Basic Authentication header
025 * to the HTTP request. Analogue of Jersey's HTTPBasicAuthFilter.
026 *
027 * If application need to write to webservices, e.g the registry, you need to make sure the user has admin rights.
028 */
029public class SimpleUserAuthRequestInterceptor implements RequestInterceptor {
030
031  private final String authentication;
032  private static final Charset CHARACTER_SET = StandardCharsets.ISO_8859_1;
033
034  /**
035   * Creates a new request interceptor using provided username
036   * and password credentials. This constructor allows you to avoid storing
037   * plain password value in a String variable.
038   */
039  public SimpleUserAuthRequestInterceptor(final String username, final byte[] password) {
040    final byte[] prefix = (username + ":").getBytes(CHARACTER_SET);
041    final byte[] usernamePassword = new byte[prefix.length + password.length];
042
043    System.arraycopy(prefix, 0, usernamePassword, 0, prefix.length);
044    System.arraycopy(password, 0, usernamePassword, prefix.length, password.length);
045
046    authentication =
047        "Basic "
048            + new String(Base64.getEncoder().encode(usernamePassword), StandardCharsets.US_ASCII);
049  }
050
051  /**
052   * Creates a new request interceptor using provided username
053   * and password credentials.
054   */
055  public SimpleUserAuthRequestInterceptor(final String username, final String password) {
056    this(username, password.getBytes(CHARACTER_SET));
057  }
058
059  @Override
060  public void apply(RequestTemplate template) {
061    template.header("Authorization", authentication);
062  }
063}