View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    *     http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  package org.gbif.ws.client;
15  
16  import java.nio.charset.Charset;
17  import java.nio.charset.StandardCharsets;
18  import java.util.Base64;
19  
20  import feign.RequestInterceptor;
21  import feign.RequestTemplate;
22  
23  /**
24   * A small request interceptor for a single, fixed user. Request Interceptor adding HTTP Basic Authentication header
25   * to the HTTP request. Analogue of Jersey's HTTPBasicAuthFilter.
26   *
27   * If application need to write to webservices, e.g the registry, you need to make sure the user has admin rights.
28   */
29  public class SimpleUserAuthRequestInterceptor implements RequestInterceptor {
30  
31    private final String authentication;
32    private static final Charset CHARACTER_SET = StandardCharsets.ISO_8859_1;
33  
34    /**
35     * Creates a new request interceptor using provided username
36     * and password credentials. This constructor allows you to avoid storing
37     * plain password value in a String variable.
38     */
39    public SimpleUserAuthRequestInterceptor(final String username, final byte[] password) {
40      final byte[] prefix = (username + ":").getBytes(CHARACTER_SET);
41      final byte[] usernamePassword = new byte[prefix.length + password.length];
42  
43      System.arraycopy(prefix, 0, usernamePassword, 0, prefix.length);
44      System.arraycopy(password, 0, usernamePassword, prefix.length, password.length);
45  
46      authentication =
47          "Basic "
48              + new String(Base64.getEncoder().encode(usernamePassword), StandardCharsets.US_ASCII);
49    }
50  
51    /**
52     * Creates a new request interceptor using provided username
53     * and password credentials.
54     */
55    public SimpleUserAuthRequestInterceptor(final String username, final String password) {
56      this(username, password.getBytes(CHARACTER_SET));
57    }
58  
59    @Override
60    public void apply(RequestTemplate template) {
61      template.header("Authorization", authentication);
62    }
63  }