View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.util;
18  
19  import java.net.URLConnection;
20  
21  import org.apache.logging.log4j.Logger;
22  import org.apache.logging.log4j.status.StatusLogger;
23  import org.apache.logging.log4j.util.Base64Util;
24  import org.apache.logging.log4j.util.LoaderUtil;
25  import org.apache.logging.log4j.util.PropertiesUtil;
26  
27  /**
28   * Provides the Basic Authorization header to a request.
29   */
30  public class BasicAuthorizationProvider implements AuthorizationProvider {
31  
32      public static final String CONFIG_USER_NAME = "log4j2.configurationUserName";
33      public static final String CONFIG_PASSWORD = "log4j2.configurationPassword";
34      public static final String PASSWORD_DECRYPTOR = "log4j2.passwordDecryptor";
35  
36      private static Logger LOGGER = StatusLogger.getLogger();
37  
38      private String authString = null;
39  
40      public BasicAuthorizationProvider(PropertiesUtil props) {
41          String userName = props.getStringProperty(CONFIG_USER_NAME);
42          String password = props.getStringProperty(CONFIG_PASSWORD);
43          String decryptor = props.getStringProperty(PASSWORD_DECRYPTOR);
44          if (decryptor != null) {
45              try {
46                  Object obj = LoaderUtil.newInstanceOf(decryptor);
47                  if (obj instanceof PasswordDecryptor) {
48                      password = ((PasswordDecryptor) obj).decryptPassword(password);
49                  }
50              } catch (Exception ex) {
51                  LOGGER.warn("Unable to decrypt password.", ex);
52              }
53          }
54          if (userName != null && password != null) {
55              authString = "Basic " + Base64Util.encode(userName + ":" + password);
56          }
57      }
58  
59      @Override
60      public void addAuthorization(URLConnection urlConnection) {
61          if (authString != null) {
62              urlConnection.setRequestProperty("Authorization", authString);
63          }
64      }
65  }