001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.core.util; 018 019import java.net.URLConnection; 020 021import org.apache.logging.log4j.Logger; 022import org.apache.logging.log4j.status.StatusLogger; 023import org.apache.logging.log4j.util.Base64Util; 024import org.apache.logging.log4j.util.LoaderUtil; 025import org.apache.logging.log4j.util.PropertiesUtil; 026 027/** 028 * Provides the Basic Authorization header to a request. 029 */ 030public class BasicAuthorizationProvider implements AuthorizationProvider { 031 032 public static final String CONFIG_USER_NAME = "log4j2.configurationUserName"; 033 public static final String CONFIG_PASSWORD = "log4j2.configurationPassword"; 034 public static final String PASSWORD_DECRYPTOR = "log4j2.passwordDecryptor"; 035 036 private static Logger LOGGER = StatusLogger.getLogger(); 037 038 private String authString = null; 039 040 public BasicAuthorizationProvider(PropertiesUtil props) { 041 String userName = props.getStringProperty(CONFIG_USER_NAME); 042 String password = props.getStringProperty(CONFIG_PASSWORD); 043 String decryptor = props.getStringProperty(PASSWORD_DECRYPTOR); 044 if (decryptor != null) { 045 try { 046 Object obj = LoaderUtil.newInstanceOf(decryptor); 047 if (obj instanceof PasswordDecryptor) { 048 password = ((PasswordDecryptor) obj).decryptPassword(password); 049 } 050 } catch (Exception ex) { 051 LOGGER.warn("Unable to decrypt password.", ex); 052 } 053 } 054 if (userName != null && password != null) { 055 authString = "Basic " + Base64Util.encode(userName + ":" + password); 056 } 057 } 058 059 @Override 060 public void addAuthorization(URLConnection urlConnection) { 061 if (authString != null) { 062 urlConnection.setRequestProperty("Authorization", authString); 063 } 064 } 065}