You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@taverna.apache.org by re...@apache.org on 2015/03/20 16:47:31 UTC

[6/8] incubator-taverna-engine git commit: package names changed to org.apache.taverna.*

http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/DefaultMasterPasswordProvider.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/DefaultMasterPasswordProvider.java b/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/DefaultMasterPasswordProvider.java
deleted file mode 100644
index 9b72188..0000000
--- a/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/DefaultMasterPasswordProvider.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import static net.sf.taverna.t2.security.credentialmanager.CredentialManager.USER_SET_MASTER_PASSWORD_INDICATOR_FILE_NAME;
-
-import java.io.File;
-
-import net.sf.taverna.t2.security.credentialmanager.MasterPasswordProvider;
-import uk.org.taverna.configuration.app.ApplicationConfiguration;
-
-//import org.apache.log4j.Logger;
-
-public class DefaultMasterPasswordProvider implements MasterPasswordProvider {
-	/**
-	 * Default master password for Credential Manager - used by default and
-	 * ignored if user sets their own
-	 */
-	private final String DEFAULT_MASTER_PASSWORD = "taverna";
-	private ApplicationConfiguration appConfig;
-
-	@Override
-	public int getProviderPriority() {
-		// Higher priority then the UI provider so this one will be tried first
-		return 101;
-	}
-
-	/**
-	 * Sets the applicationConfiguration.
-	 * 
-	 * @param applicationConfiguration
-	 *            the new value of applicationConfiguration
-	 */
-	public void setApplicationConfiguration(
-			ApplicationConfiguration applicationConfiguration) {
-		appConfig = applicationConfiguration;
-	}
-
-	@Override
-	public String getMasterPassword(boolean firstTime) {
-		File cmDir = DistinguishedNameParserImpl.getTheCredentialManagerDefaultDirectory(appConfig);
-		File flagFile = new File(cmDir,
-				USER_SET_MASTER_PASSWORD_INDICATOR_FILE_NAME);
-		if (flagFile.exists())
-			return null;
-		return DEFAULT_MASTER_PASSWORD;
-	}
-
-	@Override
-	public void setMasterPassword(String password) {
-		// We always ignore this; we're never changing our password
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/DistinguishedNameParserImpl.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/DistinguishedNameParserImpl.java b/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/DistinguishedNameParserImpl.java
deleted file mode 100644
index 5fdd8ca..0000000
--- a/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/DistinguishedNameParserImpl.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*******************************************************************************
- * Copyright (C) 2014 The University of Manchester
- *
- *  Modifications to the initial code base are copyright of their
- *  respective authors, or their employers as appropriate.
- *
- *  This program is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public License
- *  as published by the Free Software Foundation; either version 2.1 of
- *  the License, or (at your option) any later version.
- *
- *  This program is distributed in the hope that it will be useful, but
- *  WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this program; if not, write to the Free Software
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- ******************************************************************************/
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.math.BigInteger;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-
-import net.sf.taverna.t2.security.credentialmanager.CMException;
-import net.sf.taverna.t2.security.credentialmanager.DistinguishedNameParser;
-
-import org.apache.log4j.Logger;
-
-import uk.org.taverna.configuration.app.ApplicationConfiguration;
-
-/**
- * Utility methods for Credential Manager and security-related stuff.
- * 
- * @author Alex Nenadic
- * @author Stian Soiland-Reyes
- * @author Christian Brenninkmeijer
- */
-public class DistinguishedNameParserImpl implements DistinguishedNameParser{
-	private static Logger logger = Logger.getLogger(DistinguishedNameParserImpl.class);
-
-        public DistinguishedNameParserImpl(){
-        }
-        
-	/**
-	 * Get the configuration directory where the security stuff will be/is saved
-	 * to.
-	 */
-	public static File getTheCredentialManagerDefaultDirectory(
-			ApplicationConfiguration applicationConfiguration) {
-		File home = applicationConfiguration.getApplicationHomeDir();
-		File secConfigDirectory = new File(home, "security");
-		if (!secConfigDirectory.exists())
-			secConfigDirectory.mkdir();
-		return secConfigDirectory;
-	}
-
-        @Override
-	public final File getCredentialManagerDefaultDirectory(
-			ApplicationConfiguration applicationConfiguration) {
-		return getTheCredentialManagerDefaultDirectory(applicationConfiguration);
-	}
-
-        static URI resolveUriFragment(URI uri, String realm)
-			throws URISyntaxException {
-		/*
-		 * Little hack to encode the fragment correctly - why does not
-		 * java.net.URI expose this quoting or have setFragment()?
-		 */
-		URI fragment = new URI("http", "localhost", "/", realm);
-		fragment = fragment.resolve(fragment.getPath()).relativize(fragment);
-		return uri.resolve(fragment);
-	}
-
-        @Override
-	public final URI setFragmentForURI(URI uri, String fragment)
-			throws URISyntaxException {
-		return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(),
-				uri.getPort(), uri.getPath(), uri.getQuery(), fragment);
-	}
-
-        @Override
-	public final URI setUserInfoForURI(URI uri, String userinfo)
-			throws URISyntaxException {
-		return new URI(uri.getScheme(), userinfo, uri.getHost(), uri.getPort(),
-				uri.getPath(), uri.getQuery(), uri.getFragment());
-	}
-
-        @Override
-	public final X509Certificate convertCertificate(Certificate cert)
-			throws CMException {
-		try {
-			// Get the factory for X509 certificates
-			CertificateFactory cf = CertificateFactory.getInstance("X.509");
-			// Get the encoded (binary) form of the certificate.
-			// For an X509 certificate the encoding will be DER.
-			ByteArrayInputStream bais = new ByteArrayInputStream(
-					cert.getEncoded());
-			// Create the X509 certificate object from the stream
-			return (X509Certificate) cf.generateCertificate(bais);
-		} catch (CertificateException ex) {
-			throw new CMException(
-					"Failed to convert the certificate object into X.509 certificate.",
-					ex);
-		}
-	}
-
-	/**
-	 * Get the message digest of the given byte array as a string of hexadecimal
-	 * characters in the form XX:XX:XX... using the given digest algorithm.
-	 */
-	public String getMessageDigestAsFormattedString(byte[] messageBytes,
-			String digestAlgorithm) {
-
-		MessageDigest messageDigest;
-		byte[] digestBytes;
-		try {
-			messageDigest = MessageDigest.getInstance(digestAlgorithm);
-			digestBytes = messageDigest.digest(messageBytes);
-		} catch (NoSuchAlgorithmException ex) {
-			logger.error("Failed to create message digest.", ex);
-			return "";
-		}
-
-		// Create the integer value from the digest bytes
-		BigInteger number = new BigInteger(1, digestBytes);
-		// Convert the integer from decimal to hexadecimal representation
-		String hexValueString = number.toString(16).toUpperCase();
-
-		StringBuffer strBuff = new StringBuffer(hexValueString);
-		// If the hex number contains odd number of characters -
-		// insert a padding "0" at the front of the string
-		if ((strBuff.length() % 2) != 0)
-			strBuff.insert(0, '0');
-
-		// Insert colons after every two hex characters - start form the end of
-		// the hex string
-		if (strBuff.length() > 2)
-			for (int i = 2; i < strBuff.length(); i += 3)
-				strBuff.insert(i, ':');
-
-		return strBuff.toString();
-	}
-
-
-	private String emailAddress; // not from RFC 2253, yet some certificates
-									// contain this field
-
-	private String CN;
-	private String L;
-	private String ST;
-	private String C;
-	private String O;
-	private String OU;
-
-	/**
-	 * Parses a DN string and fills in fields with DN parts. Heavily based on
-	 * uk.ac.omii.security.utils.DNParser class from omii-security-utils
-	 * library.
-	 * 
-	 * http://maven.omii.ac.uk/maven2/repository/omii/omii-security-utils/
-	 */
-	public ParsedDistinguishedNameImpl parseDN(String DNstr) {
-            return new ParsedDistinguishedNameImpl(DNstr);
-        }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/ParsedDistinguishedNameImpl.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/ParsedDistinguishedNameImpl.java b/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/ParsedDistinguishedNameImpl.java
deleted file mode 100644
index c049d49..0000000
--- a/taverna-credential-manager-impl/src/main/java/net/sf/taverna/t2/security/credentialmanager/impl/ParsedDistinguishedNameImpl.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*******************************************************************************
- * Copyright (C) 2014 The University of Manchester
- *
- *  Modifications to the initial code base are copyright of their
- *  respective authors, or their employers as appropriate.
- *
- *  This program is free software; you can redistribute it and/or
- *  modify it under the terms of the GNU Lesser General Public License
- *  as published by the Free Software Foundation; either version 2.1 of
- *  the License, or (at your option) any later version.
- *
- *  This program is distributed in the hope that it will be useful, but
- *  WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- *  Lesser General Public License for more details.
- *
- *  You should have received a copy of the GNU Lesser General Public
- *  License along with this program; if not, write to the Free Software
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- ******************************************************************************/
-package net.sf.taverna.t2.security.credentialmanager.impl;
-
-import java.net.URI;
-import java.util.ArrayList;
-import net.sf.taverna.t2.security.credentialmanager.ParsedDistinguishedName;
-import org.apache.log4j.Logger;
-
-/**
- * Parses a Distinguished Name and stores the parts for retreival.
- * 
- * @author Alex Nenadic
- * @author Stian Soiland-Reyes
- * @author Christian Brenninkmeijer
- */
-public class ParsedDistinguishedNameImpl implements ParsedDistinguishedName{
-	private static final Logger logger = Logger.getLogger(ParsedDistinguishedNameImpl.class);
-
-	private String emailAddress; // not from RFC 2253, yet some certificates
-									// contain this field
-	private String CN;
-	private String L;
-	private String ST;
-	private String C;
-	private String O;
-	private String OU;
-
-	// /**
-	// * Gets the intended certificate uses, i.e. Netscape Certificate Type
-	// * extension (2.16.840.1.113730.1.1) as a string.
-	// */
-	// // From openssl's documentation: "The [above] extension is non standard,
-	// Netscape
-	// // specific and largely obsolete. Their use in new applications is
-	// discouraged."
-	// // TODO replace with "basicConstraints, keyUsage and extended key usage
-	// extensions
-	// // which are now used instead."
-	// public static String getIntendedCertificateUses(byte[] value) {
-	//
-	// // Netscape Certificate Types (2.16.840.1.113730.1.1) denoting the
-	// // intended uses of a certificate
-	// int[] INTENDED_USES = new int[] { NetscapeCertType.sslClient,
-	// NetscapeCertType.sslServer, NetscapeCertType.smime,
-	// NetscapeCertType.objectSigning, NetscapeCertType.reserved,
-	// NetscapeCertType.sslCA, NetscapeCertType.smimeCA,
-	// NetscapeCertType.objectSigningCA, };
-	//
-	// // Netscape Certificate Type strings (2.16.840.1.113730.1.1)
-	// HashMap<String, String> INTENDED_USES_STRINGS = new HashMap<String,
-	// String>();
-	// INTENDED_USES_STRINGS.put("128", "SSL Client");
-	// INTENDED_USES_STRINGS.put("64", "SSL Server");
-	// INTENDED_USES_STRINGS.put("32", "S/MIME");
-	// INTENDED_USES_STRINGS.put("16", "Object Signing");
-	// INTENDED_USES_STRINGS.put("8", "Reserved");
-	// INTENDED_USES_STRINGS.put("4", "SSL CA");
-	// INTENDED_USES_STRINGS.put("2", "S/MIME CA");
-	// INTENDED_USES_STRINGS.put("1", "Object Signing CA");
-	//
-	// // Get DER octet string from extension value
-	// ASN1OctetString derOctetString = new DEROctetString(value);
-	// byte[] octets = derOctetString.getOctets();
-	// // Get DER bit string
-	// DERBitString derBitString = new DERBitString(octets);
-	// int val = new NetscapeCertType(derBitString).intValue();
-	// StringBuffer strBuff = new StringBuffer();
-	// for (int i = 0, len = INTENDED_USES.length; i < len; i++) {
-	// int use = INTENDED_USES[i];
-	// if ((val & use) == use) {
-	// strBuff.append(INTENDED_USES_STRINGS.get(String.valueOf(use))
-	// + ", \n");
-	// }
-	// }
-	// // remove the last ", \n" from the end of the buffer
-	// String str = strBuff.toString();
-	// str = str.substring(0, str.length() - 3);
-	// return str;
-	// }
-
-	// FROM RFC 2253:
-	// CN commonName
-	// L localityName
-	// ST stateOrProvinceName
-	// O organizationName
-	// OU organizationalUnitName
-	// C countryName
-	// STREET streetAddress
-	// DC domainComponent
-	// UID userid
-
-        /**
-	 * Parses a DN string and fills in fields with DN parts. Heavily based on
-	 * uk.ac.omii.security.utils.DNParser class from omii-security-utils
-	 * library.
-	 * 
-	 * http://maven.omii.ac.uk/maven2/repository/omii/omii-security-utils/
-	 */
-	public ParsedDistinguishedNameImpl(String DNstr) {
-		// ///////////////////////////////////////////////////////////////////////////////////////////////////
-		// Parse the DN String and put into variables. First, tokenise using a
-		// "," character as a delimiter
-		// UNLESS escaped with a "\" character. Put the tokens into an
-		// ArrayList. These should be name value pairs
-		// separated by "=". Tokenise these using a StringTokenizer class, test
-		// for the name, and if one of the
-		// recognised names, copy into the correct variable. The reason
-		// StringTokenizer is not used for the major
-		// token list is that the StringTokenizer class does not handle escaped
-		// delimiters so an escaped delimiter
-		// in the code would be treated as a valid one.
-
-		int i = 0;
-
-		char majorListDelimiter = ',';
-		char majorListEscapeChar = '\\';
-
-		// String minorListDelimiter = "=";
-
-		String DNchars = DNstr;
-
-		int startIndex = 0;
-		int endIndex = 0;
-		boolean ignoreThisChar = false;
-
-		boolean inQuotes = false;
-
-		ArrayList<String> majorTokenList = new ArrayList<String>();
-
-		for (i = 0; i < DNchars.length(); i++) {
-			if (ignoreThisChar == true) {
-				ignoreThisChar = false;
-			} else if ((inQuotes == false) && (DNchars.charAt(i) == '\"')) {
-				inQuotes = true;
-			} else if ((inQuotes == true) && (DNchars.charAt(i) == '\"')) {
-				inQuotes = false;
-			} else if (inQuotes == true) {
-				continue;
-			} else if (DNchars.charAt(i) == majorListEscapeChar) {
-				ignoreThisChar = true;
-			} else if ((DNchars.charAt(i) == majorListDelimiter)
-					&& (ignoreThisChar == false)) {
-				endIndex = i;
-				majorTokenList.add(DNchars.substring(startIndex, endIndex));
-				startIndex = i + 1;
-			}
-		}
-
-		// Add last token - after the last delimiter
-		endIndex = DNchars.length();
-		majorTokenList.add(DNchars.substring(startIndex, endIndex));
-
-		for (String currentToken : majorTokenList) {
-			currentToken = currentToken.trim();
-
-			// split on first equals only, as value can contain an equals char
-			String[] minorTokenList = currentToken.split("=", 2);
-
-			if (minorTokenList.length == 2) {
-				// there had better be a key and a value only
-				String DNTokenName = minorTokenList[0].toUpperCase();
-				String DNTokenValue = minorTokenList[1];
-
-				if (DNTokenName.equals("CN")
-						|| DNTokenName.equals("COMMONNAME")) {
-					CN = DNTokenValue;
-				} else if (DNTokenName.equals("EMAIL")
-						|| DNTokenName.equals("EMAILADDRESS")) {
-					emailAddress = DNTokenValue;
-				} else if (DNTokenName.equals("OU")
-						|| DNTokenName.equals("ORGANIZATIONALUNITNAME")) {
-					OU = DNTokenValue;
-				} else if (DNTokenName.equals("O")
-						|| DNTokenName.equals("ORGANIZATIONNAME")) {
-					O = DNTokenValue;
-				} else if (DNTokenName.equals("L")
-						|| DNTokenName.equals("LOCALITYNAME")) {
-					L = DNTokenValue;
-				} else if (DNTokenName.equals("ST")
-						|| DNTokenName.equals("STATEORPROVINCENAME")) {
-					ST = DNTokenValue;
-				} else if (DNTokenName.equals("C")
-						|| DNTokenName.equals("COUNTRYNAME")) {
-					C = DNTokenValue;
-				}
-			}
-			// else we have a key with no value, so skip processing the key
-		}
-
-		if (CN == null)
-			CN = "none";
-
-		if (emailAddress == null)
-			emailAddress = "none";
-
-		if (OU == null)
-			OU = "none";
-
-		if (O == null)
-			O = "none";
-
-		if (L == null)
-			L = "none";
-
-		if (ST == null)
-			ST = "none";
-
-		if (C == null)
-			C = "none";
-	}
-
-        @Override
-	public String getCN() {
-		return CN;
-	}
-
-        @Override
-	public String getEmailAddress() {
-		return emailAddress;
-	}
-
-        @Override
-	public String getOU() {
-		return OU;
-	}
-
-        @Override
-	public String getO() {
-		return O;
-	}
-
-        @Override
-	public String getL() {
-		return L;
-	}
-
-        @Override
-	public String getST() {
-		return ST;
-	}
-
-        @Override
-	public String getC() {
-		return C;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-taverna-engine/blob/55900be9/taverna-credential-manager-impl/src/main/java/org/apache/taverna/security/credentialmanager/impl/CredentialManagerAuthenticator.java
----------------------------------------------------------------------
diff --git a/taverna-credential-manager-impl/src/main/java/org/apache/taverna/security/credentialmanager/impl/CredentialManagerAuthenticator.java b/taverna-credential-manager-impl/src/main/java/org/apache/taverna/security/credentialmanager/impl/CredentialManagerAuthenticator.java
new file mode 100644
index 0000000..59bbfaa
--- /dev/null
+++ b/taverna-credential-manager-impl/src/main/java/org/apache/taverna/security/credentialmanager/impl/CredentialManagerAuthenticator.java
@@ -0,0 +1,131 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.taverna.security.credentialmanager.impl;
+
+import static java.net.Authenticator.RequestorType.PROXY;
+
+import java.net.Authenticator;
+import java.net.PasswordAuthentication;
+import java.net.URI;
+import java.net.URISyntaxException;
+import org.apache.taverna.security.credentialmanager.CMException;
+import org.apache.taverna.security.credentialmanager.CredentialManager;
+import org.apache.taverna.security.credentialmanager.UsernamePassword;
+
+import org.apache.log4j.Logger;
+
+/**
+ * Credential Manager backed {@link Authenticator}.
+ * <p>
+ * Initialize by using: <code>
+ * Authenticator.setDefault(new CredentialManagerAuthenticator());
+ * </code>
+ * <p>
+ * Special case included for proxy authentication.
+ * 
+ * @author Stian Soiland-Reyes
+ * 
+ */
+public class CredentialManagerAuthenticator extends Authenticator {
+	private Logger logger;
+	private CredentialManager credManager;
+
+	public CredentialManagerAuthenticator(CredentialManager credManager) {
+		logger = Logger.getLogger(CredentialManagerAuthenticator.class);
+		setCredentialManager(credManager);
+	}
+
+	public void setCredentialManager(CredentialManager credManager) {
+		this.credManager = credManager;
+	}
+
+	@Override
+	protected PasswordAuthentication getPasswordAuthentication() {
+		if (getRequestorType().equals(PROXY)) {
+			String password = System.getProperty("http.proxyPassword");
+			String username = System.getProperty("http.proxyUser");
+			if (username == null || password == null)
+				// No proxy authentication set
+				return null;
+
+			return new PasswordAuthentication(username, password.toCharArray());
+		}
+
+		URI uri;
+		if (getRequestingURL() != null) {
+			try {
+				uri = getRequestingURL().toURI();
+			} catch (URISyntaxException e) {
+				logger.warn("Unsupported request (invalid URL) for "
+						+ getRequestingURL());
+				return null;
+			}
+		} else {
+			// Construct an URI of socket://hostname:port
+			String host = getRequestingHost();
+			if (host == null)
+				// Use IP address
+				host = getRequestingSite().getHostAddress();
+			int port = getRequestingPort();
+			if (host == null || port < 0) {
+				logger.warn("Unsupported request for " + getRequestingScheme()
+						+ " " + getRequestingSite());
+				return null;
+			}
+			uri = URI.create("socket://" + host + ":" + port);
+		}
+
+		if (credManager == null) {
+			logger.warn("No Credential Manager");
+			return null;
+		}
+		boolean usePathRecursion = false;
+		String realm = getRequestingPrompt();
+		if (getRequestingScheme().equals("basic")
+				|| getRequestingScheme().equals("digest")) {
+			usePathRecursion = true;
+			if (realm != null && realm.length() > 0)
+				try {
+					uri = DistinguishedNameParserImpl.resolveUriFragment(uri, realm);
+				} catch (URISyntaxException e) {
+					logger.warn("Could not URI-encode fragment for realm: "
+							+ realm);
+				}
+		}
+
+		UsernamePassword usernameAndPassword;
+		try {
+			usernameAndPassword = credManager.getUsernameAndPasswordForService(uri,
+					usePathRecursion, realm);
+		} catch (CMException e) {
+			logger.warn("Could not get username and password for " + uri, e);
+			return null;
+		}
+		if (usernameAndPassword == null) {
+			logger.warn("No username/password found for " + uri);
+			return null;
+		}
+		PasswordAuthentication pwAuth = new PasswordAuthentication(
+				usernameAndPassword.getUsername(), usernameAndPassword
+						.getPassword());
+		usernameAndPassword.resetPassword();
+		return pwAuth;
+	}
+}