hc-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ol...@apache.org
Subject svn commit: r527479 - in /jakarta/httpcomponents/httpclient/trunk/src: java/org/apache/http/auth/ java/org/apache/http/impl/auth/ test/org/apache/http/impl/auth/
Date Wed, 11 Apr 2007 12:55:14 GMT
Author: olegk
Date: Wed Apr 11 05:55:12 2007
New Revision: 527479

URL: http://svn.apache.org/viewvc?view=rev&rev=527479
Log:
Ported DigestScheme and related test cases from Commons HttpClient

Added:
    jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/DigestScheme.java
      - copied, changed from r527154, jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/auth/DigestScheme.java
    jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java   (with props)
    jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestDigestAuth.java
      - copied, changed from r527154, jakarta/commons/proper/httpclient/trunk/src/test/org/apache/commons/httpclient/auth/TestDigestAuth.java
Modified:
    jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/AuthScheme.java
    jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/Credentials.java
    jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/UsernamePasswordCredentials.java
    jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/BasicScheme.java
    jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/RFC2617Scheme.java
    jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestAllAuthImpl.java
    jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestBasicAuth.java
    jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestRFC2617Scheme.java

Modified: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/AuthScheme.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/AuthScheme.java?view=diff&rev=527479&r1=527478&r2=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/AuthScheme.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/AuthScheme.java Wed Apr 11 05:55:12 2007
@@ -31,7 +31,7 @@
 package org.apache.http.auth;
 
 import org.apache.http.Header;
-import org.apache.http.HttpMessage;
+import org.apache.http.HttpRequest;
 
 /**
  * <p>
@@ -128,13 +128,13 @@
      * Produces an authorization string for the given set of {@link Credentials}.
      * 
      * @param credentials The set of credentials to be used for athentication
-     * @param message The request being authenticated
+     * @param request The request being authenticated
      * @throws AuthenticationException if authorization string cannot 
      *   be generated due to an authentication failure
      * 
      * @return the authorization string
      */
-    Header authenticate(Credentials credentials, HttpMessage message) 
+    Header authenticate(Credentials credentials, HttpRequest request) 
             throws AuthenticationException;
     
 }

Modified: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/Credentials.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/Credentials.java?view=diff&rev=527479&r1=527478&r2=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/Credentials.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/Credentials.java Wed Apr 11 05:55:12 2007
@@ -31,7 +31,7 @@
 package org.apache.http.auth;
 
 /**
- * <p>Authentication credentials.</p>
+ * User name and password based authentication credentials.
  * 
  * @author Unascribed
  * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
@@ -39,12 +39,9 @@
  * @version $Revision$ $Date$
  */
 public interface Credentials {
-    
-    /** Returns textual representation of the user credentials, which, for instance,
-     * could be sent in the {@link HTTPAuth#WWW_AUTH} header.
-     * 
-     * @return user credentials as a string of text
-     */ 
-    String toText();
+
+    String getPrincipalName();
+
+    String getPassword();
     
 }

Modified: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/UsernamePasswordCredentials.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/UsernamePasswordCredentials.java?view=diff&rev=527479&r1=527478&r2=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/UsernamePasswordCredentials.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/auth/UsernamePasswordCredentials.java Wed Apr 11 05:55:12 2007
@@ -106,7 +106,7 @@
      * @return the userName
      * @see #setUserName(String)
      */
-    public String getUserName() {
+    public String getPrincipalName() {
         return userName;
     }
 

Modified: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/BasicScheme.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/BasicScheme.java?view=diff&rev=527479&r1=527478&r2=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/BasicScheme.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/BasicScheme.java Wed Apr 11 05:55:12 2007
@@ -32,7 +32,7 @@
 
 import org.apache.commons.codec.binary.Base64;
 import org.apache.http.Header;
-import org.apache.http.HttpMessage;
+import org.apache.http.HttpRequest;
 import org.apache.http.auth.AuthenticationException;
 import org.apache.http.auth.Credentials;
 import org.apache.http.auth.HTTPAuth;
@@ -89,7 +89,7 @@
      * @throws MalformedChallengeException is thrown if the authentication challenge
      * is malformed
      * 
-     * @since 3.0
+     * @since 4.0
      */
     public void processChallenge(
             final Header header) throws MalformedChallengeException {
@@ -124,7 +124,7 @@
      * Produces basic authorization header for the given set of {@link Credentials}.
      * 
      * @param credentials The set of credentials to be used for athentication
-     * @param message The message being authenticated
+     * @param request The request being authenticated
      * @throws InvalidCredentialsException if authentication credentials
      *         are not valid or not applicable for this authentication scheme
      * @throws AuthenticationException if authorization string cannot 
@@ -136,17 +136,17 @@
      */
     public Header authenticate(
             final Credentials credentials, 
-            final HttpMessage message) throws AuthenticationException {
+            final HttpRequest request) throws AuthenticationException {
 
         if (credentials == null) {
             throw new IllegalArgumentException("Credentials may not be null");
         }
-        if (message == null) {
-            throw new IllegalArgumentException("HTTP message may not be null");
+        if (request == null) {
+            throw new IllegalArgumentException("HTTP request may not be null");
         }
         
-        String charset = AuthParams.getCredentialCharset(message.getParams());
-        return authenticate(credentials, charset);
+        String charset = AuthParams.getCredentialCharset(request.getParams());
+        return authenticate(credentials, charset, isProxy());
     }
     
     /**
@@ -160,22 +160,33 @@
      * 
      * @since 4.0
      */
-    public static Header authenticate(final Credentials credentials, final String charset) {
+    public static Header authenticate(
+            final Credentials credentials, 
+            final String charset, 
+            boolean proxy) {
         if (credentials == null) {
             throw new IllegalArgumentException("Credentials may not be null"); 
         }
         if (charset == null) {
             throw new IllegalArgumentException("charset may not be null");
         }
+
         CharArrayBuffer buffer = new CharArrayBuffer(32);
-        buffer.append(HTTPAuth.WWW_AUTH_RESP);
-        buffer.append(": ");
-        buffer.append("Basic ");
-        
-        byte[] passwd = Base64.encodeBase64(
-                EncodingUtils.getBytes(credentials.toText(), charset));
+        buffer.append(credentials.getPrincipalName());
+        buffer.append(":");
+        buffer.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
+
+        byte[] base64password = Base64.encodeBase64(
+                EncodingUtils.getBytes(buffer.toString(), charset));
         
-        buffer.append(passwd, 0, passwd.length);
+        buffer.clear();
+        if (proxy) {
+            buffer.append(HTTPAuth.PROXY_AUTH_RESP);
+        } else {
+            buffer.append(HTTPAuth.WWW_AUTH_RESP);
+        }
+        buffer.append(": Basic ");
+        buffer.append(base64password, 0, base64password.length);
         
         return new BufferedHeader(buffer);
     }

Copied: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/DigestScheme.java (from r527154, jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/auth/DigestScheme.java)
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/DigestScheme.java?view=diff&rev=527479&p1=jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/auth/DigestScheme.java&r1=527154&p2=jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/DigestScheme.java&r2=527479
==============================================================================
--- jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/auth/DigestScheme.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/DigestScheme.java Wed Apr 11 05:55:12 2007
@@ -1,5 +1,5 @@
 /*
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/DigestScheme.java,v 1.22 2004/12/30 11:01:27 oglueck Exp $
+ * $HeadURL$
  * $Revision$
  * $Date$
  *
@@ -28,23 +28,24 @@
  *
  */
 
-package org.apache.commons.httpclient.auth;
+package org.apache.http.impl.auth;
 
 import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.StringTokenizer;
 
-import org.apache.commons.httpclient.Credentials;
-import org.apache.commons.httpclient.HttpClientError;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.NameValuePair;
-import org.apache.commons.httpclient.UsernamePasswordCredentials;
-import org.apache.commons.httpclient.util.EncodingUtil;
-import org.apache.commons.httpclient.util.ParameterFormatter;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import org.apache.http.Header;
+import org.apache.http.HttpRequest;
+import org.apache.http.auth.AuthenticationException;
+import org.apache.http.auth.Credentials;
+import org.apache.http.auth.HTTPAuth;
+import org.apache.http.auth.MalformedChallengeException;
+import org.apache.http.auth.params.AuthParams;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.message.BufferedHeader;
+import org.apache.http.util.CharArrayBuffer;
+import org.apache.http.util.EncodingUtils;
 
 /**
  * <p>
@@ -62,23 +63,19 @@
  * {@link org.apache.commons.httpclient.params.HttpMethodParams#HTTP_ELEMENT_CHARSET http element 
  * charset}.
  * </p>
- * TODO: make class more stateful regarding repeated authentication requests
  * 
  * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
  * @author Rodney Waldhoff
  * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
- * @author Ortwin Gl?ck
+ * @author Ortwin Glueck
  * @author Sean C. Sullivan
  * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
  * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
- * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
  */
 
 public class DigestScheme extends RFC2617Scheme {
     
-    /** Log object for this class. */
-    private static final Log LOG = LogFactory.getLog(DigestScheme.class);
-
     /**
      * Hexa values used when creating 32 character long digest in HTTP DigestScheme
      * in case of authentication.
@@ -102,7 +99,6 @@
     private int qopVariant = QOP_MISSING;
     private String cnonce;
 
-    private final ParameterFormatter formatter;
     /**
      * Default constructor for the digest authetication scheme.
      * 
@@ -111,42 +107,6 @@
     public DigestScheme() {
         super();
         this.complete = false;
-        this.formatter = new ParameterFormatter();
-    }
-
-    /**
-     * Gets an ID based upon the realm and the nonce value.  This ensures that requests
-     * to the same realm with different nonce values will succeed.  This differentiation
-     * allows servers to request re-authentication using a fresh nonce value.
-     * 
-     * @deprecated no longer used
-     */
-    public String getID() {
-        
-        String id = getRealm();
-        String nonce = getParameter("nonce");
-        if (nonce != null) {
-            id += "-" + nonce;
-        }
-        
-        return id;
-    }
-
-    /**
-     * Constructor for the digest authetication scheme.
-     * 
-     * @param challenge authentication challenge
-     * 
-     * @throws MalformedChallengeException is thrown if the authentication challenge
-     * is malformed
-     * 
-     * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} 
-     *             method
-     */
-    public DigestScheme(final String challenge) 
-      throws MalformedChallengeException {
-        this();
-        processChallenge(challenge);
     }
 
     /**
@@ -157,11 +117,11 @@
      * @throws MalformedChallengeException is thrown if the authentication challenge
      * is malformed
      * 
-     * @since 3.0
+     * @since 4.0
      */
-    public void processChallenge(final String challenge) 
-      throws MalformedChallengeException {
-        super.processChallenge(challenge);
+    public void processChallenge(
+            final Header header) throws MalformedChallengeException {
+        super.processChallenge(header);
         
         if (getParameter("realm") == null) {
             throw new MalformedChallengeException("missing realm in challange");
@@ -184,7 +144,6 @@
                     qopVariant = QOP_AUTH_INT;               
                 } else {
                     unsupportedQop = true;
-                    LOG.warn("Unsupported qop detected: "+ variant);   
                 }     
             }
         }        
@@ -239,47 +198,6 @@
      * {@link Credentials}, method name and URI.
      * 
      * @param credentials A set of credentials to be used for athentication
-     * @param method the name of the method that requires authorization. 
-     * @param uri The URI for which authorization is needed. 
-     * 
-     * @throws InvalidCredentialsException if authentication credentials
-     *         are not valid or not applicable for this authentication scheme
-     * @throws AuthenticationException if authorization string cannot 
-     *   be generated due to an authentication failure
-     * 
-     * @return a digest authorization string
-     * 
-     * @see org.apache.commons.httpclient.HttpMethod#getName()
-     * @see org.apache.commons.httpclient.HttpMethod#getPath()
-     * 
-     * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
-     */
-    public String authenticate(Credentials credentials, String method, String uri)
-      throws AuthenticationException {
-
-        LOG.trace("enter DigestScheme.authenticate(Credentials, String, String)");
-
-        UsernamePasswordCredentials usernamepassword = null;
-        try {
-            usernamepassword = (UsernamePasswordCredentials) credentials;
-        } catch (ClassCastException e) {
-            throw new InvalidCredentialsException(
-             "Credentials cannot be used for digest authentication: " 
-              + credentials.getClass().getName());
-        }
-        getParameters().put("methodname", method);
-        getParameters().put("uri", uri);
-        String digest = createDigest(
-            usernamepassword.getUserName(),
-            usernamepassword.getPassword());
-        return "Digest " + createDigestHeader(usernamepassword.getUserName(), digest);
-    }
-
-    /**
-     * Produces a digest authorization string for the given set of 
-     * {@link Credentials}, method name and URI.
-     * 
-     * @param credentials A set of credentials to be used for athentication
      * @param method The method being authenticated
      * 
      * @throws InvalidCredentialsException if authentication credentials
@@ -289,40 +207,40 @@
      * 
      * @return a digest authorization string
      * 
-     * @since 3.0
+     * @since 4.0
      */
-    public String authenticate(Credentials credentials, HttpMethod method)
-    throws AuthenticationException {
-
-        LOG.trace("enter DigestScheme.authenticate(Credentials, HttpMethod)");
+    public Header authenticate(
+            final Credentials credentials, 
+            final HttpRequest request) throws AuthenticationException {
 
-        UsernamePasswordCredentials usernamepassword = null;
-        try {
-            usernamepassword = (UsernamePasswordCredentials) credentials;
-        } catch (ClassCastException e) {
-            throw new InvalidCredentialsException(
-                    "Credentials cannot be used for digest authentication: " 
-                    + credentials.getClass().getName());
-        }
-        getParameters().put("methodname", method.getName());
-        StringBuffer buffer = new StringBuffer(method.getPath());
-        String query = method.getQueryString();
-        if (query != null) {
-            if (query.indexOf("?") != 0) {
-                buffer.append("?");
-            }
-            buffer.append(method.getQueryString());
+        if (credentials == null) {
+            throw new IllegalArgumentException("Credentials may not be null");
+        }
+        if (request == null) {
+            throw new IllegalArgumentException("HTTP request may not be null");
         }
-        getParameters().put("uri", buffer.toString());
+        
+        // Add method name and request-URI to the parameter map
+        getParameters().put("methodname", request.getRequestLine().getMethod());
+        getParameters().put("uri", request.getRequestLine().getUri());
         String charset = getParameter("charset");
         if (charset == null) {
-            getParameters().put("charset", method.getParams().getCredentialCharset());
+            charset = AuthParams.getCredentialCharset(request.getParams());
+            getParameters().put("charset", charset);
+        }
+        String digest = createDigest(credentials);
+        return createDigestHeader(credentials, digest);
+    }
+    
+    private static MessageDigest createMessageDigest(
+            final String digAlg) throws UnsupportedDigestAlgorithmException {
+        try {
+            return MessageDigest.getInstance(digAlg);
+        } catch (Exception e) {
+            throw new UnsupportedDigestAlgorithmException(
+              "Unsupported algorithm in HTTP Digest authentication: "
+               + digAlg);
         }
-        String digest = createDigest(
-            usernamepassword.getUserName(),
-            usernamepassword.getPassword());
-        return "Digest " + createDigestHeader(usernamepassword.getUserName(),
-                digest);
     }
     
     /**
@@ -336,17 +254,11 @@
      *         value in the Authentication HTTP header.
      * @throws AuthenticationException when MD5 is an unsupported algorithm
      */
-    private String createDigest(final String uname, final String pwd) throws AuthenticationException {
-
-        LOG.trace("enter DigestScheme.createDigest(String, String, Map)");
-
-        final String digAlg = "MD5";
-
+    private String createDigest(final Credentials credentials) throws AuthenticationException {
         // Collecting required tokens
         String uri = getParameter("uri");
         String realm = getParameter("realm");
         String nonce = getParameter("nonce");
-        String qop = getParameter("qop");
         String method = getParameter("methodname");
         String algorithm = getParameter("algorithm");
         // If an algorithm is not specified, default to MD5.
@@ -360,23 +272,17 @@
         }
 
         if (qopVariant == QOP_AUTH_INT) {
-            LOG.warn("qop=auth-int is not supported");
             throw new AuthenticationException(
                 "Unsupported qop in HTTP Digest authentication");   
         }
 
-        MessageDigest md5Helper;
-
-        try {
-            md5Helper = MessageDigest.getInstance(digAlg);
-        } catch (Exception e) {
-            throw new AuthenticationException(
-              "Unsupported algorithm in HTTP Digest authentication: "
-               + digAlg);
-        }
+        MessageDigest md5Helper = createMessageDigest("MD5");
 
+        String uname = credentials.getPrincipalName();
+        String pwd = credentials.getPassword();
+        
         // 3.2.2.2: Calculating digest
-        StringBuffer tmp = new StringBuffer(uname.length() + realm.length() + pwd.length() + 2);
+        CharArrayBuffer tmp = new CharArrayBuffer(uname.length() + realm.length() + pwd.length() + 2);
         tmp.append(uname);
         tmp.append(':');
         tmp.append(realm);
@@ -390,34 +296,33 @@
             //      ":" unq(nonce-value)
             //      ":" unq(cnonce-value)
 
-            String tmp2=encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
-            StringBuffer tmp3 = new StringBuffer(tmp2.length() + nonce.length() + cnonce.length() + 2);
+            String tmp2=encode(md5Helper.digest(EncodingUtils.getBytes(a1, charset)));
+            CharArrayBuffer tmp3 = new CharArrayBuffer(tmp2.length() + nonce.length() + cnonce.length() + 2);
             tmp3.append(tmp2);
             tmp3.append(':');
             tmp3.append(nonce);
             tmp3.append(':');
             tmp3.append(cnonce);
             a1 = tmp3.toString();
-        } else if(!algorithm.equals("MD5")) {
-            LOG.warn("Unhandled algorithm " + algorithm + " requested");
+        } else if (!algorithm.equals("MD5")) {
+            throw new AuthenticationException("Unhandled algorithm " + algorithm + " requested");
         }
-        String md5a1 = encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
+        String md5a1 = encode(md5Helper.digest(EncodingUtils.getBytes(a1, charset)));
 
         String a2 = null;
         if (qopVariant == QOP_AUTH_INT) {
-            LOG.error("Unhandled qop auth-int");
+            // Unhandled qop auth-int
             //we do not have access to the entity-body or its hash
             //TODO: add Method ":" digest-uri-value ":" H(entity-body)      
         } else {
             a2 = method + ":" + uri;
         }
-        String md5a2 = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(a2)));
+        String md5a2 = encode(md5Helper.digest(EncodingUtils.getAsciiBytes(a2)));
 
         // 3.2.2.1
         String serverDigestValue;
         if (qopVariant == QOP_MISSING) {
-            LOG.debug("Using null qop method");
-            StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length() + md5a2.length());
+            CharArrayBuffer tmp2 = new CharArrayBuffer(md5a1.length() + nonce.length() + md5a2.length());
             tmp2.append(md5a1);
             tmp2.append(':');
             tmp2.append(nonce);
@@ -425,11 +330,8 @@
             tmp2.append(md5a2);
             serverDigestValue = tmp2.toString();
         } else {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Using qop method " + qop);
-            }
             String qopOption = getQopVariantString();
-            StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length()
+            CharArrayBuffer tmp2 = new CharArrayBuffer(md5a1.length() + nonce.length()
                 + NC.length() + cnonce.length() + qopOption.length() + md5a2.length() + 5);
             tmp2.append(md5a1);
             tmp2.append(':');
@@ -446,7 +348,7 @@
         }
 
         String serverDigest =
-            encode(md5Helper.digest(EncodingUtil.getAsciiBytes(serverDigestValue)));
+            encode(md5Helper.digest(EncodingUtils.getAsciiBytes(serverDigestValue)));
 
         return serverDigest;
     }
@@ -454,17 +356,23 @@
     /**
      * Creates digest-response header as defined in RFC2617.
      * 
-     * @param uname Username
+     * @param credentials User credentials
      * @param digest The response tag's value as String.
      * 
      * @return The digest-response as String.
      */
-    private String createDigestHeader(final String uname, final String digest) 
-        throws AuthenticationException {
-
-        LOG.trace("enter DigestScheme.createDigestHeader(String, Map, "
-            + "String)");
-
+    private Header createDigestHeader(
+            final Credentials credentials, 
+            final String digest) throws AuthenticationException {
+        
+        CharArrayBuffer buffer = new CharArrayBuffer(128);
+        if (isProxy()) {
+            buffer.append(HTTPAuth.PROXY_AUTH_RESP);
+        } else {
+            buffer.append(HTTPAuth.WWW_AUTH_RESP);
+        }
+        buffer.append(": Digest ");
+        
         String uri = getParameter("uri");
         String realm = getParameter("realm");
         String nonce = getParameter("nonce");
@@ -473,36 +381,34 @@
         String algorithm = getParameter("algorithm");
 
         List params = new ArrayList(20);
-        params.add(new NameValuePair("username", uname));
-        params.add(new NameValuePair("realm", realm));
-        params.add(new NameValuePair("nonce", nonce));
-        params.add(new NameValuePair("uri", uri));
-        params.add(new NameValuePair("response", response));
+        params.add(new BasicNameValuePair("username", credentials.getPrincipalName()));
+        params.add(new BasicNameValuePair("realm", realm));
+        params.add(new BasicNameValuePair("nonce", nonce));
+        params.add(new BasicNameValuePair("uri", uri));
+        params.add(new BasicNameValuePair("response", response));
         
         if (qopVariant != QOP_MISSING) {
-            params.add(new NameValuePair("qop", getQopVariantString()));
-            params.add(new NameValuePair("nc", NC));
-            params.add(new NameValuePair("cnonce", this.cnonce));
+            params.add(new BasicNameValuePair("qop", getQopVariantString()));
+            params.add(new BasicNameValuePair("nc", NC));
+            params.add(new BasicNameValuePair("cnonce", this.cnonce));
         }
         if (algorithm != null) {
-            params.add(new NameValuePair("algorithm", algorithm));
+            params.add(new BasicNameValuePair("algorithm", algorithm));
         }    
         if (opaque != null) {
-            params.add(new NameValuePair("opaque", opaque));
+            params.add(new BasicNameValuePair("opaque", opaque));
         }
 
-        StringBuffer buffer = new StringBuffer();
         for (int i = 0; i < params.size(); i++) {
-            NameValuePair param = (NameValuePair) params.get(i);
+            BasicNameValuePair param = (BasicNameValuePair) params.get(i);
             if (i > 0) {
                 buffer.append(", ");
             }
             boolean noQuotes = "nc".equals(param.getName()) ||
                                "qop".equals(param.getName());
-            this.formatter.setAlwaysUseQuotes(!noQuotes);
-            this.formatter.format(buffer, param);
+            BasicNameValuePair.format(buffer, param, !noQuotes);
         }
-        return buffer.toString();
+        return new BufferedHeader(buffer);
     }
 
     private String getQopVariantString() {
@@ -523,8 +429,6 @@
      * @return encoded MD5, or <CODE>null</CODE> if encoding failed
      */
     private static String encode(byte[] binaryData) {
-        LOG.trace("enter DigestScheme.encode(byte[])");
-
         if (binaryData.length != 16) {
             return null;
         } 
@@ -548,22 +452,12 @@
      * @throws HttpClientError if MD5 algorithm is not supported.
      */
     public static String createCnonce() {
-        LOG.trace("enter DigestScheme.createCnonce()");
-
         String cnonce;
-        final String digAlg = "MD5";
-        MessageDigest md5Helper;
 
-        try {
-            md5Helper = MessageDigest.getInstance(digAlg);
-        } catch (NoSuchAlgorithmException e) {
-            throw new HttpClientError(
-              "Unsupported algorithm in HTTP Digest authentication: "
-               + digAlg);
-        }
+        MessageDigest md5Helper = createMessageDigest("MD5");
 
         cnonce = Long.toString(System.currentTimeMillis());
-        cnonce = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(cnonce)));
+        cnonce = encode(md5Helper.digest(EncodingUtils.getAsciiBytes(cnonce)));
 
         return cnonce;
     }

Modified: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/RFC2617Scheme.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/RFC2617Scheme.java?view=diff&rev=527479&r1=527478&r2=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/RFC2617Scheme.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/RFC2617Scheme.java Wed Apr 11 05:55:12 2007
@@ -60,6 +60,11 @@
     private Map params = null;
 
     /**
+     * Flag whether authenticating against a proxy.
+     */
+    private boolean proxy;
+    
+    /**
      * Default constructor for RFC2617 compliant authetication schemes.
      * 
      * @since 3.0
@@ -85,10 +90,14 @@
             throw new IllegalArgumentException("Header may not be null");
         }
         String authheader = header.getName();
-        if (!authheader.equalsIgnoreCase(HTTPAuth.WWW_AUTH) 
-                && !authheader.equalsIgnoreCase(HTTPAuth.PROXY_AUTH)) {
+        if (authheader.equalsIgnoreCase(HTTPAuth.WWW_AUTH)) {
+            this.proxy = false;
+        } else if (authheader.equalsIgnoreCase(HTTPAuth.PROXY_AUTH)) {
+            this.proxy = true;
+        } else {
             throw new MalformedChallengeException("Unexpected header name: " + authheader);
         }
+
         CharArrayBuffer buffer;
         int pos;
         if (header instanceof BufferedHeader) {
@@ -160,6 +169,17 @@
      */
     public String getRealm() {
         return getParameter("realm");
+    }
+
+    /**
+     * Returns <code>true</code> if authenticating against a proxy, <code>false</code>
+     * otherwise.
+     *  
+     * @return <code>true</code> if authenticating against a proxy, <code>false</code>
+     * otherwise
+     */
+    public boolean isProxy() {
+        return this.proxy;
     }
     
 }

Added: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java?view=auto&rev=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java (added)
+++ jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java Wed Apr 11 05:55:12 2007
@@ -0,0 +1,71 @@
+/*
+ * $HeadURL$
+ * $Revision$
+ * $Date$
+ *
+ * ====================================================================
+ *
+ *  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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.http.impl.auth;
+
+/**
+ * Authentication credentials required to respond to a authentication 
+ * challenge are invalid
+ *
+ * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
+ * 
+ * @since 4.0
+ */
+public class UnsupportedDigestAlgorithmException extends RuntimeException {
+
+    private static final long serialVersionUID = 319558534317118022L;
+
+    /**
+     * Creates a new UnsupportedAuthAlgoritmException with a <tt>null</tt> detail message. 
+     */
+    public UnsupportedDigestAlgorithmException() {
+        super();
+    }
+
+    /**
+     * Creates a new UnsupportedAuthAlgoritmException with the specified message.
+     * 
+     * @param message the exception detail message
+     */
+    public UnsupportedDigestAlgorithmException(String message) {
+        super(message);
+    }
+
+    /**
+     * Creates a new UnsupportedAuthAlgoritmException with the specified detail message and cause.
+     * 
+     * @param message the exception detail message
+     * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
+     * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
+     */
+    public UnsupportedDigestAlgorithmException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}

Propchange: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: jakarta/httpcomponents/httpclient/trunk/src/java/org/apache/http/impl/auth/UnsupportedDigestAlgorithmException.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestAllAuthImpl.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestAllAuthImpl.java?view=diff&rev=527479&r1=527478&r2=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestAllAuthImpl.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestAllAuthImpl.java Wed Apr 11 05:55:12 2007
@@ -45,6 +45,7 @@
 
         suite.addTest(TestRFC2617Scheme.suite());
         suite.addTest(TestBasicAuth.suite());
+        suite.addTest(TestDigestAuth.suite());
 
         return suite;
     }

Modified: jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestBasicAuth.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestBasicAuth.java?view=diff&rev=527479&r1=527478&r2=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestBasicAuth.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestBasicAuth.java Wed Apr 11 05:55:12 2007
@@ -37,14 +37,13 @@
 
 import org.apache.commons.codec.binary.Base64;
 import org.apache.http.Header;
-import org.apache.http.HttpMessage;
-import org.apache.http.HttpVersion;
+import org.apache.http.HttpRequest;
 import org.apache.http.auth.AuthScheme;
 import org.apache.http.auth.HTTPAuth;
 import org.apache.http.auth.MalformedChallengeException;
 import org.apache.http.auth.UsernamePasswordCredentials;
 import org.apache.http.message.BasicHeader;
-import org.apache.http.message.BasicHttpResponse;
+import org.apache.http.message.BasicHttpRequest;
 import org.apache.http.util.EncodingUtils;
 
 /**
@@ -94,7 +93,7 @@
         }
         
         UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("dh", buffer.toString());
-        Header header = BasicScheme.authenticate(credentials, "ISO-8859-1");
+        Header header = BasicScheme.authenticate(credentials, "ISO-8859-1", false);
         assertEquals("Basic ZGg65C32Lfw=", header.getValue());
     }
     
@@ -107,11 +106,33 @@
         BasicScheme authscheme = new BasicScheme();
         authscheme.processChallenge(challenge);
         
-        HttpMessage message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
-        Header authResponse = authscheme.authenticate(creds, message);
+        HttpRequest request = new BasicHttpRequest("GET", "/");
+        Header authResponse = authscheme.authenticate(creds, request);
         
         String expected = "Basic " + EncodingUtils.getAsciiString(
             Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
+        assertEquals(HTTPAuth.WWW_AUTH_RESP, authResponse.getName());
+        assertEquals(expected, authResponse.getValue());
+        assertEquals("test", authscheme.getRealm());
+        assertTrue(authscheme.isComplete());
+        assertFalse(authscheme.isConnectionBased());
+    }
+
+    public void testBasicProxyAuthentication() throws Exception {
+        UsernamePasswordCredentials creds = 
+            new UsernamePasswordCredentials("testuser", "testpass");
+        
+        Header challenge = new BasicHeader(HTTPAuth.PROXY_AUTH, "Basic realm=\"test\"");
+        
+        BasicScheme authscheme = new BasicScheme();
+        authscheme.processChallenge(challenge);
+        
+        HttpRequest request = new BasicHttpRequest("GET", "/");
+        Header authResponse = authscheme.authenticate(creds, request);
+        
+        String expected = "Basic " + EncodingUtils.getAsciiString(
+            Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
+        assertEquals(HTTPAuth.PROXY_AUTH_RESP, authResponse.getName());
         assertEquals(expected, authResponse.getValue());
         assertEquals("test", authscheme.getRealm());
         assertTrue(authscheme.isComplete());

Copied: jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestDigestAuth.java (from r527154, jakarta/commons/proper/httpclient/trunk/src/test/org/apache/commons/httpclient/auth/TestDigestAuth.java)
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestDigestAuth.java?view=diff&rev=527479&p1=jakarta/commons/proper/httpclient/trunk/src/test/org/apache/commons/httpclient/auth/TestDigestAuth.java&r1=527154&p2=jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestDigestAuth.java&r2=527479
==============================================================================
--- jakarta/commons/proper/httpclient/trunk/src/test/org/apache/commons/httpclient/auth/TestDigestAuth.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestDigestAuth.java Wed Apr 11 05:55:12 2007
@@ -1,5 +1,5 @@
 /*
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestDigestAuth.java,v 1.2 2004/11/07 12:31:42 olegk Exp $
+ * $HeadURL$
  * $Revision$
  * $Date$
  * ====================================================================
@@ -27,28 +27,27 @@
  * 
  */
 
-package org.apache.commons.httpclient.auth;
+package org.apache.http.impl.auth;
 
-import java.io.IOException;
+import java.util.HashMap;
 import java.util.Map;
 
-import org.apache.commons.httpclient.FakeHttpMethod;
-import org.apache.commons.httpclient.Header;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.HttpVersion;
-import org.apache.commons.httpclient.UsernamePasswordCredentials;
-import org.apache.commons.httpclient.protocol.Protocol;
-import org.apache.commons.httpclient.server.HttpService;
-import org.apache.commons.httpclient.server.RequestLine;
-import org.apache.commons.httpclient.server.SimpleHttpServer;
-import org.apache.commons.httpclient.server.SimpleRequest;
-import org.apache.commons.httpclient.server.SimpleResponse;
-
 import junit.framework.Test;
 import junit.framework.TestCase;
 import junit.framework.TestSuite;
 
+import org.apache.http.Header;
+import org.apache.http.HeaderElement;
+import org.apache.http.HttpRequest;
+import org.apache.http.auth.AuthScheme;
+import org.apache.http.auth.Credentials;
+import org.apache.http.auth.HTTPAuth;
+import org.apache.http.auth.MalformedChallengeException;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.message.BasicHeader;
+import org.apache.http.message.BasicHeaderElement;
+import org.apache.http.message.BasicHttpRequest;
+
 /**
  * Test Methods for DigestScheme Authentication.
  *
@@ -76,10 +75,10 @@
     }
 
     public void testDigestAuthenticationWithNoRealm() throws Exception {
-        String challenge = "Digest";
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, "Digest");
         try {
             AuthScheme authscheme = new DigestScheme();
-            authscheme.processChallenge(challenge);
+            authscheme.processChallenge(authChallenge);
             fail("Should have thrown MalformedChallengeException");
         } catch(MalformedChallengeException e) {
             // expected
@@ -87,10 +86,10 @@
     }
 
     public void testDigestAuthenticationWithNoRealm2() throws Exception {
-        String challenge = "Digest ";
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, "Digest ");
         try {
             AuthScheme authscheme = new DigestScheme();
-            authscheme.processChallenge(challenge);
+            authscheme.processChallenge(authChallenge);
             fail("Should have thrown MalformedChallengeException");
         } catch(MalformedChallengeException e) {
             // expected
@@ -99,12 +98,14 @@
 
     public void testDigestAuthenticationWithDefaultCreds() throws Exception {
         String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
-        FakeHttpMethod method = new FakeHttpMethod("/");
-        UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password");
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
+        HttpRequest request = new BasicHttpRequest("Simple", "/");
+        Credentials cred = new UsernamePasswordCredentials("username","password");
         AuthScheme authscheme = new DigestScheme();
-        authscheme.processChallenge(challenge);
-        String response = authscheme.authenticate(cred, method);
-        Map table = AuthChallengeParser.extractParams(response);
+        authscheme.processChallenge(authChallenge);
+        Header authResponse = authscheme.authenticate(cred, request);
+
+        Map table = parseAuthResponse(authResponse);
         assertEquals("username", table.get("username"));
         assertEquals("realm1", table.get("realm"));
         assertEquals("/", table.get("uri"));
@@ -114,12 +115,14 @@
 
     public void testDigestAuthentication() throws Exception {
         String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
-        UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password");
-        FakeHttpMethod method = new FakeHttpMethod("/");
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
+        HttpRequest request = new BasicHttpRequest("Simple", "/");
+        Credentials cred = new UsernamePasswordCredentials("username","password");
         AuthScheme authscheme = new DigestScheme();
-        authscheme.processChallenge(challenge);
-        String response = authscheme.authenticate(cred, method);
-        Map table = AuthChallengeParser.extractParams(response);
+        authscheme.processChallenge(authChallenge);
+        Header authResponse = authscheme.authenticate(cred, request);
+
+        Map table = parseAuthResponse(authResponse);
         assertEquals("username", table.get("username"));
         assertEquals("realm1", table.get("realm"));
         assertEquals("/", table.get("uri"));
@@ -129,13 +132,14 @@
 
     public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception {
         String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
-        UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password");
-        FakeHttpMethod method = new FakeHttpMethod("/");
-        method.setQueryString("param=value");
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
+        HttpRequest request = new BasicHttpRequest("Simple", "/?param=value");
+        Credentials cred = new UsernamePasswordCredentials("username","password");
         AuthScheme authscheme = new DigestScheme();
-        authscheme.processChallenge(challenge);
-        String response = authscheme.authenticate(cred, method);
-        Map table = AuthChallengeParser.extractParams(response);
+        authscheme.processChallenge(authChallenge);
+        Header authResponse = authscheme.authenticate(cred, request);
+
+        Map table = parseAuthResponse(authResponse);
         assertEquals("username", table.get("username"));
         assertEquals("realm1", table.get("realm"));
         assertEquals("/?param=value", table.get("uri"));
@@ -146,24 +150,28 @@
     public void testDigestAuthenticationWithMultipleRealms() throws Exception {
         String challenge1 = "Digest realm=\"realm1\", nonce=\"abcde\"";
         String challenge2 = "Digest realm=\"realm2\", nonce=\"123546\"";
-        UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password");
-        UsernamePasswordCredentials cred2 = new UsernamePasswordCredentials("uname2","password2");
+        Credentials cred = new UsernamePasswordCredentials("username","password");
+        Credentials cred2 = new UsernamePasswordCredentials("uname2","password2");
+
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge1);
+        HttpRequest request = new BasicHttpRequest("Simple", "/");
+        AuthScheme authscheme = new DigestScheme();
+        authscheme.processChallenge(authChallenge);
+        Header authResponse = authscheme.authenticate(cred, request);
 
-        FakeHttpMethod method = new FakeHttpMethod("/");
-        AuthScheme authscheme1 = new DigestScheme();
-        authscheme1.processChallenge(challenge1);
-        String response1 = authscheme1.authenticate(cred, method);
-        Map table = AuthChallengeParser.extractParams(response1);
+        Map table = parseAuthResponse(authResponse);
         assertEquals("username", table.get("username"));
         assertEquals("realm1", table.get("realm"));
         assertEquals("/", table.get("uri"));
         assertEquals("abcde", table.get("nonce"));
         assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response"));
 
+        authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge2);
         AuthScheme authscheme2 = new DigestScheme();
-        authscheme2.processChallenge(challenge2);
-        String response2 = authscheme2.authenticate(cred2, method);
-        table = AuthChallengeParser.extractParams(response2);
+        authscheme2.processChallenge(authChallenge);
+        authResponse = authscheme2.authenticate(cred2, request);
+
+        table = parseAuthResponse(authResponse);
         assertEquals("uname2", table.get("username"));
         assertEquals("realm2", table.get("realm"));
         assertEquals("/", table.get("uri"));
@@ -189,16 +197,20 @@
             + "algorithm=MD5-sess, "
             + "qop=\"auth,auth-int\""; // we pass both but expect auth to be used
 
-        UsernamePasswordCredentials cred =
-            new UsernamePasswordCredentials(username, password);
-        FakeHttpMethod method = new FakeHttpMethod("/");
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
+        
+        Credentials cred = new UsernamePasswordCredentials(username, password);
+        HttpRequest request = new BasicHttpRequest("Simple", "/");
 
         AuthScheme authscheme = new DigestScheme();
-        authscheme.processChallenge(challenge);
-        String response = authscheme.authenticate(cred, method);
+        authscheme.processChallenge(authChallenge);
+        Header authResponse = authscheme.authenticate(cred, request);
+        String response = authResponse.getValue();
+        
         assertTrue(response.indexOf("nc=00000001") > 0); // test for quotes
         assertTrue(response.indexOf("qop=auth") > 0); // test for quotes
-        Map table = AuthChallengeParser.extractParams(response);
+
+        Map table = parseAuthResponse(authResponse);
         assertEquals(username, table.get("username"));
         assertEquals(realm, table.get("realm"));
         assertEquals("MD5-sess", table.get("algorithm"));
@@ -229,15 +241,17 @@
             + "stale=false, "
             + "algorithm=MD5-sess";
 
-        UsernamePasswordCredentials cred =
-            new UsernamePasswordCredentials(username, password);
-        FakeHttpMethod method = new FakeHttpMethod("/");
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
+        
+        Credentials cred = new UsernamePasswordCredentials(username, password);
+
+        HttpRequest request = new BasicHttpRequest("Simple", "/");
 
         AuthScheme authscheme = new DigestScheme();
-        authscheme.processChallenge(challenge);
-        String response = authscheme.authenticate(cred, method);
+        authscheme.processChallenge(authChallenge);
+        Header authResponse = authscheme.authenticate(cred, request);
 
-        Map table = AuthChallengeParser.extractParams(response);
+        Map table = parseAuthResponse(authResponse);
         assertEquals(username, table.get("username"));
         assertEquals(realm, table.get("realm"));
         assertEquals("MD5-sess", table.get("algorithm"));
@@ -257,8 +271,6 @@
         // Example using Digest auth with MD5-sess
 
         String realm="realm";
-        String username="username";
-        String password="password";
         String nonce="e273f1776275974f1a120d8b92c5b3cb";
 
         String challenge="Digest realm=\"" + realm + "\", "
@@ -268,84 +280,38 @@
             + "algorithm=MD5-sess, "
             + "qop=\"jakarta\""; // jakarta is an invalid qop value
 
-        UsernamePasswordCredentials cred =
-            new UsernamePasswordCredentials(username, password);
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
+        
         try {
             AuthScheme authscheme = new DigestScheme();
-            authscheme.processChallenge(challenge);
+            authscheme.processChallenge(authChallenge);
             fail("MalformedChallengeException exception expected due to invalid qop value");
         } catch(MalformedChallengeException e) {
         }
     }
 
-    private class StaleNonceService implements HttpService {
-
-        public StaleNonceService() {
-            super();
-        }
+    public void testDigestAuthenticationWithStaleNonce() throws Exception {
+        String challenge = "Digest realm=\"realm1\", " +
+                "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", stale=\"true\"";
+        Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
+        AuthScheme authscheme = new DigestScheme();
+        authscheme.processChallenge(authChallenge);
 
-        public boolean process(final SimpleRequest request, final SimpleResponse response)
-            throws IOException
-        {
-            RequestLine requestLine = request.getRequestLine();
-            HttpVersion ver = requestLine.getHttpVersion();
-            Header auth = request.getFirstHeader("Authorization");
-            if (auth == null) { 
-                response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED);
-                response.addHeader(new Header("WWW-Authenticate", 
-                        "Digest realm=\"realm1\", nonce=\"ABC123\""));
-                response.setBodyString("Authorization required");
-                return true;
-            } else {
-                Map table = AuthChallengeParser.extractParams(auth.getValue());
-                String nonce = (String)table.get("nonce");
-                if (nonce.equals("ABC123")) {
-                    response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED);
-                    response.addHeader(new Header("WWW-Authenticate", 
-                            "Digest realm=\"realm1\", nonce=\"321CBA\", stale=\"true\""));
-                    response.setBodyString("Authorization required");
-                    return true;
-                } else {
-                    response.setStatusLine(ver, HttpStatus.SC_OK);
-                    response.setBodyString("Authorization successful");
-                    return true;
-                }
-            }
-        }
+        assertFalse(authscheme.isComplete());
     }
 
-    
-    public void testDigestAuthenticationWithStaleNonce() throws Exception {
-        // configure the server
-        SimpleHttpServer server = new SimpleHttpServer(); // use arbitrary port
-        server.setTestname(getName());
-        server.setHttpService(new StaleNonceService());
-
-        // configure the client
-        HttpClient client = new HttpClient();
-        client.getHostConfiguration().setHost(
-                server.getLocalAddress(), server.getLocalPort(),
-                Protocol.getProtocol("http"));
-        
-        client.getState().setCredentials(AuthScope.ANY, 
-                new UsernamePasswordCredentials("username","password"));
-        
-        FakeHttpMethod httpget = new FakeHttpMethod("/");
-        try {
-            client.executeMethod(httpget);
-        } finally {
-            httpget.releaseConnection();
+    private static Map parseAuthResponse(final Header authResponse) {
+        String s = authResponse.getValue();
+        if (!s.startsWith("Digest ")) {
+            return null;
         }
-        assertNotNull(httpget.getStatusLine());
-        assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
-        Map table = AuthChallengeParser.extractParams(
-                httpget.getRequestHeader("Authorization").getValue());
-        assertEquals("username", table.get("username"));
-        assertEquals("realm1", table.get("realm"));
-        assertEquals("/", table.get("uri"));
-        assertEquals("321CBA", table.get("nonce"));
-        assertEquals("7f5948eefa115296e9279225041527b3", table.get("response"));
-        server.destroy();
+        HeaderElement[] elements = BasicHeaderElement.parseAll(s.substring(7));
+        Map map = new HashMap(elements.length);
+        for (int i = 0; i < elements.length; i++) {
+            HeaderElement element = elements[i];
+            map.put(element.getName(), element.getValue());
+        }
+        return map;
     }
-
+    
 }

Modified: jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestRFC2617Scheme.java
URL: http://svn.apache.org/viewvc/jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestRFC2617Scheme.java?view=diff&rev=527479&r1=527478&r2=527479
==============================================================================
--- jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestRFC2617Scheme.java (original)
+++ jakarta/httpcomponents/httpclient/trunk/src/test/org/apache/http/impl/auth/TestRFC2617Scheme.java Wed Apr 11 05:55:12 2007
@@ -31,7 +31,7 @@
 package org.apache.http.impl.auth;
 
 import org.apache.http.Header;
-import org.apache.http.HttpMessage;
+import org.apache.http.HttpRequest;
 import org.apache.http.auth.AuthenticationException;
 import org.apache.http.auth.Credentials;
 import org.apache.http.auth.HTTPAuth;
@@ -63,7 +63,7 @@
 
         public Header authenticate(
                 final Credentials credentials, 
-                final HttpMessage message) throws AuthenticationException {
+                final HttpRequest request) throws AuthenticationException {
             return null;
         }
 



Mime
View raw message