commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jeri...@apache.org
Subject cvs commit: jakarta-commons/httpclient/src/java/org/apache/commons/httpclient Authenticator.java
Date Wed, 23 Oct 2002 16:15:44 GMT
jericho     2002/10/23 09:15:43

  Modified:    httpclient/src/java/org/apache/commons/httpclient
                        Authenticator.java
  Log:
  - Code cleanup (local variable naming changes, remove tabs, etc...)
     I hope there are no typos...
  
  - Apply Adrian Sutton's patch for NTLM along with host
  His comment:
  Currently NTLM authentication always uses the default credentials.  This is
  annoying if you need to connect to mulitple NTLM servers with different
  credentials.  The attached patch uses the hostname to track the credentials
  as retrieved from the Host header.
  
  Revision  Changes    Path
  1.31      +270 -243  jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Authenticator.java
  
  Index: Authenticator.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Authenticator.java,v
  retrieving revision 1.30
  retrieving revision 1.31
  diff -u -r1.30 -r1.31
  --- Authenticator.java	30 Sep 2002 19:42:13 -0000	1.30
  +++ Authenticator.java	23 Oct 2002 16:15:43 -0000	1.31
  @@ -90,40 +90,61 @@
    * </blockquote>
    * </p>
    * 
  - * @version $Revision$ $Date$
    * @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 Sean C. Sullivan
    * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
  - * 
  + * @version $Revision$ $Date$
    */
  -class Authenticator {
  -    //~ Static variables/initializers ииииииииииииииииииииииииииииииииииииииииии
  +public class Authenticator {
   
  -    /** <tt>org.apache.commons.httpclient.Authenticator</tt> log. */
  +    // -------------------------------------- Static variables and initializers
  +
  +    /**
  +     * <tt>org.apache.commons.httpclient.Authenticator</tt> log.
  +     */
       private static final Log log = LogFactory.getLog(Authenticator.class);
   
  -    /** The boolean property name to turn on preemptive authentication. */
  -    static final String PREEMPTIVE_PROPERTY = 
  +
  +    /**
  +     * The boolean property name to turn on preemptive authentication.
  +     */
  +    private static final String PREEMPTIVE_PROPERTY = 
           "httpclient.authentication.preemptive";
   
  -    /** The default property value for #PREEMPTIVE_PROPERTY. */
  -    static final String PREEMPTIVE_DEFAULT = "false";
   
  -    /** The www authenticate challange header */
  +    /**
  +     * The default property value for #PREEMPTIVE_PROPERTY.
  +     */
  +    private static final String PREEMPTIVE_DEFAULT = "false";
  +
  +
  +    /**
  +     * The www authenticate challange header.
  +     */
       public static final String WWW_AUTH = "WWW-Authenticate";
   
  -    /** The www authenticate response header */
  +
  +    /**
  +     * The www authenticate response header.
  +     */
       public static final String WWW_AUTH_RESP = "Authorization";
   
  -    /** The proxy authenticate challange header */
  +
  +    /**
  +     * The proxy authenticate challange header.
  +     */
       public static final String PROXY_AUTH = "Proxy-Authenticate";
   
  -    /** The proxy authenticate response header */
  +
  +    /**
  +     * The proxy authenticate response header.
  +     */
       public static final String PROXY_AUTH_RESP = "Proxy-Authorization";
   
  +
       /**
        * Hexa values used when creating 32 character long digest in HTTP Digest
        * in case of authentication.
  @@ -135,39 +156,36 @@
           'e', 'f'
       };
   
  -    //~ Methods ииииииииииииииииииииииииииииииииииииииииииииииииииииииииииииииии
  +    // ---------------------------------------------------------------- Methods
   
       /**
        * Creates an MD5 response digest.
        * 
        * @param uname Username
        * @param pwd Password
  -     * @param mapCreds map containing necessary header parameters to
  +     * @param mapCredentials map containing necessary header parameters to
        *        construct the digest. It must/can contain: uri, realm, nonce,
        *        cnonce, qop, nc.
  -     * 
        * @return The created digest as string. This will be the response tag's
        *         value in the Authentication HTTP header.
        * @throws HttpException when MD5 is an unsupported algorithm
  -     * 
        * @todo + Add createDigest() method 
        */
  -    public static String createDigest(String uname, String pwd, 
  -                                      Map mapCreds)
  -                               throws HttpException {
  -        log.trace("enter Authenticator.createDigest(String, String, "
  -            + "Map)");
  +    public static String createDigest(String uname, String pwd,
  +            Map mapCredentials) throws HttpException {
  +
  +        log.trace("enter Authenticator.createDigest(String, String, Map)");
   
           final String digAlg = "MD5";
   
           // Collecting required tokens
  -        String uri = removeQuotes((String) mapCreds.get("uri"));
  -        String realm = removeQuotes((String) mapCreds.get("realm"));
  -        String nonce = removeQuotes((String) mapCreds.get("nonce"));
  -        String nc = removeQuotes((String) mapCreds.get("nc"));
  -        String cnonce = removeQuotes((String) mapCreds.get("cnonce"));
  -        String qop = removeQuotes((String) mapCreds.get("qop"));
  -        String method = (String) mapCreds.get("methodname");
  +        String uri = removeQuotes((String) mapCredentials.get("uri"));
  +        String realm = removeQuotes((String) mapCredentials.get("realm"));
  +        String nonce = removeQuotes((String) mapCredentials.get("nonce"));
  +        String nc = removeQuotes((String) mapCredentials.get("nc"));
  +        String cnonce = removeQuotes((String) mapCredentials.get("cnonce"));
  +        String qop = removeQuotes((String) mapCredentials.get("qop"));
  +        String method = (String) mapCredentials.get("methodname");
   
           if (qop != null) {
               qop = "auth";
  @@ -198,30 +216,29 @@
                                   + ":" + qop + ":" + md5a2;
           }
   
  -        String serverDigest = encode(md5Helper.digest(
  -                                             serverDigestValue.getBytes()));
  +        String serverDigest =
  +            encode(md5Helper.digest(serverDigestValue.getBytes()));
   
           return serverDigest;
       }
   
  +
       /**
        * Add requisite authentication credentials to the given <i>method</i>
in
        * the given <i>state</i> if possible.
        * 
        * @param method the HttpMethod which requires authentication
        * @param state the HttpState object providing Credentials
  -     * 
        * @return true if the Authenticate response header was added
  -     * 
        * @throws HttpException when a parsing or other error occurs
        * @throws UnsupportedOperationException when the challenge type is not
        *         supported
  -     * 
        * @see HttpState#setCredentials(String,Credentials)
        * @see #authenticate(HttpMethod,HttpState,Header,String)
        */
  -    static boolean authenticate(HttpMethod method, HttpState state)
  -                         throws HttpException, UnsupportedOperationException {
  +    public static boolean authenticate(HttpMethod method, HttpState state)
  +        throws HttpException, UnsupportedOperationException {
  +
           log.trace("enter Authenticator.authenticate(HttpMethod, HttpState)");
   
           Header challengeHeader = method.getResponseHeader(WWW_AUTH);
  @@ -229,25 +246,23 @@
           return authenticate(method, state, challengeHeader, WWW_AUTH_RESP);
       }
   
  +
       /**
        * Add requisite proxy authentication credentials to the given
        * <i>method</i> in the given <i>state</i> if possible.
        * 
        * @param method the HttpMethod which requires authentication
        * @param state the HttpState object providing Credentials
  -     * 
        * @return true if the Authenticate response header was added
  -     * 
        * @throws HttpException when a parsing or other error occurs
        * @throws UnsupportedOperationException when the given challenge type is
        *         not supported
  -     * 
        * @see HttpState#setProxyCredentials(String,Credentials)
        * @see #authenticate(HttpMethod,HttpState,Header,String)
        */
  -    static boolean authenticateProxy(HttpMethod method, HttpState state)
  -                              throws HttpException, 
  -                                     UnsupportedOperationException {
  +    public static boolean authenticateProxy(HttpMethod method, HttpState state)
  +        throws HttpException, UnsupportedOperationException {
  +
           log.trace("enter Authenticator.authenticateProxy(HttpMethod, "
                     + "HttpState)");
   
  @@ -256,115 +271,137 @@
           return authenticate(method, state, challengeHeader, PROXY_AUTH_RESP);
       }
   
  +
       /**
        * Return a Basic <tt>Authorization</tt> header value for the given {@link
        * UsernamePasswordCredentials}.
        * 
  -     * @param cred the credentials to encode. Must be non-null
  -     * 
  +     * @param credentials the credentials to encode. Must be non-null
        * @return the credentials as a Basic Authentication string
        */
  -    static String basic(UsernamePasswordCredentials cred) {
  +    private static String basic(UsernamePasswordCredentials credentials) {
           log.trace("enter Authenticator.basic(UsernamePasswordCredentials)");
   
  -        String authString = cred.getUserName() + ":" + cred.getPassword();
  +        String authString = credentials.getUserName() + ":" +
  +            credentials.getPassword();
   
           return "Basic " + new String(Base64.encode(authString.getBytes()));
       }
   
  +
       /**
        * Create a Basic <tt>Authorization</tt> header for the given <i>realm</i>
        * and <i>state</i> to the given <i>method</i>.
        * 
        * @param realm the basic realm to authenticate to
        * @param state a {@link HttpState} object providing {@link Credentials}
  -     * @param respHeader the header's name to store the authentication response
  -     *        in. PROXY_AUTH_RESP will force the proxy credentials to be used.
  -     * 
  +     * @param responseHeader the header's name to store the authentication
  +     *        response in. PROXY_AUTH_RESP will force the proxy credentials to
  +     *        be used.
        * @return a basic <tt>Authorization</tt> header
  -     * 
        * @throws HttpException when no matching credentials are available
        */
  -    static Header basic(String realm, HttpState state, String respHeader)
  -                 throws HttpException {
  +    private static Header basic(String realm, HttpState state,
  +            String responseHeader) throws HttpException {
  +
           log.trace("enter Authenticator.basic(String, HttpState, String)");
   
  -        boolean proxy = PROXY_AUTH_RESP.equals(respHeader);
  -        UsernamePasswordCredentials cred = null;
  +        boolean proxy = PROXY_AUTH_RESP.equals(responseHeader);
  +        UsernamePasswordCredentials credentials = null;
   
           try {
  -            cred = (UsernamePasswordCredentials) (proxy
  -                ? state.getProxyCredentials(realm)
  -                : state.getCredentials(realm));
  +            credentials = (UsernamePasswordCredentials) (proxy ?
  +                    state.getProxyCredentials(realm) :
  +                    state.getCredentials(realm));
           } catch (ClassCastException e) {
               throw new HttpException("UsernamePasswordCredentials required for "
                                       + "Basic authentication.");
           }
   
  -        if (null == cred) {
  +        if (credentials == null) {
               throw new HttpException("No credentials available for the Basic "
                                       + "authentication realm \'" + realm + "\'");
  -        } else {
  -            return new Header(respHeader, Authenticator.basic(cred));
           }
  +        // else
  +        return new Header(responseHeader, Authenticator.basic(credentials));
       }
   
  +
       /**
  -	 * Create a NTLM <tt>Authorization</tt> header for the given
  -	 * <i>Challenge</i> and <i>state</i> to the given <i>method</i>.
  -	 *
  -	 * @param method the {@link HttpMethod request} requiring the ntlm
  -	 * @param state a {@link HttpState} object providing
  -	 * {@link Credentials}
  -	 * @param respHeader the header's name to store the authentication
  -	 * response in.  PROXY_AUTH_RESP will force the proxy credentials to
  -	 * be used.
  -	 *
  -	 * @return a ntlm <tt>Authorization</tt> header
  -	 *
  -	 * @throws HttpException when no matching credentials are available
  -	 */
  -	static Header ntlm(String challenge, HttpMethod method, HttpState state,
  -                         String respHeader) throws HttpException {
  +     * Create a NTLM <tt>Authorization</tt> header for the given
  +     * <i>Challenge</i> and <i>state</i> to the given <i>method</i>.
  +     *
  +     * @param method the {@link HttpMethod request} requiring the ntlm
  +     * @param state a {@link HttpState} object providing
  +     * {@link Credentials}
  +     * @param responseHeader the header's name to store the authentication
  +     * response in.  PROXY_AUTH_RESP will force the proxy credentials to
  +     * be used.
  +     * @return a ntlm <tt>Authorization</tt> header
  +     * @throws HttpException when no matching credentials are available
  +     */
  +    private static Header ntlm(String challenge, HttpMethod method,
  +            HttpState state, String responseHeader) throws HttpException {
  +
           log.trace("enter Authenticator.ntlm(String, HttpMethod, HttpState, "
                     + "String)");
   
  -        boolean proxy = PROXY_AUTH_RESP.equals(respHeader);
  -        NTCredentials cred = null;
  +        boolean proxy = PROXY_AUTH_RESP.equals(responseHeader);
   
  -        try {
  -            cred = (NTCredentials) (proxy
  -                ? state.getProxyCredentials(null)
  -                : state.getCredentials(null));
  -        } catch (ClassCastException e) {
  -            throw new HttpException("NTCredentials required "
  -                                    + "for NTLM authentication.");
  +        NTCredentials credentials = null;
  +
  +        if (method.getRequestHeader("Host") != null) {
  +            String host = method.getRequestHeader("Host").getValue();
  +            try {
  +                credentials = (NTCredentials) (proxy ?
  +                        state.getProxyCredentials(host) :
  +                        state.getCredentials(host));
  +            } catch (ClassCastException e) {
  +                throw new HttpException("NTCredentials required "
  +                                        + "for NTLM authentication.");
  +            }
           }
   
  -		try {
  -			challenge = challenge.substring(challenge.toLowerCase().indexOf("ntlm") + "ntlm".length()).trim();
  -		} catch (IndexOutOfBoundsException e) {
  -			throw new HttpException("Invalid NTLM challenge.");
  -		}
  +        if (credentials == null) {
  +            log.info("No credentials for specific host, " +
  +                    "attempting to use default credentials.");
  +            try {
  +                credentials = (NTCredentials) (proxy ?
  +                        state.getProxyCredentials(null) :
  +                        state.getCredentials(null));
  +            } catch (ClassCastException e) {
  +                throw new HttpException(
  +                        "NTCredentials required for NTLM authentication.");
  +            }
  +        }
  +
  +        try {
  +            challenge =
  +                challenge.substring(challenge.toLowerCase().indexOf("ntlm") +
  +                        "ntlm".length()).trim();
  +        } catch (IndexOutOfBoundsException e) {
  +            throw new HttpException("Invalid NTLM challenge.");
  +        }
   
  -        if (null == cred) {
  +        if (credentials == null) {
               throw new HttpException("No credentials available for NTLM "
                   + "authentication.");
           } else {
  -			try {
  -				String resp = "NTLM " + NTLM.getResponseFor(challenge,
  -						cred.getUserName(), cred.getPassword(), cred.getHost(),
  -						cred.getDomain());
  -				if (log.isDebugEnabled()) {
  -					log.debug("Replying to challenge with: " + resp);
  -				}
  -				return new Header(respHeader, resp);
  -			} catch (java.io.UnsupportedEncodingException e) {
  -				throw new HttpException("NTLM requires ASCII support.");
  -			}
  +            try {
  +                String response = "NTLM " + NTLM.getResponseFor(challenge,
  +                        credentials.getUserName(), credentials.getPassword(),
  +                        credentials.getHost(), credentials.getDomain());
  +                if (log.isDebugEnabled()) {
  +                    log.debug("Replying to challenge with: " + response);
  +                }
  +                return new Header(responseHeader, response);
  +            } catch (java.io.UnsupportedEncodingException e) {
  +                throw new HttpException("NTLM requires ASCII support.");
  +            }
           }
       }
   
  +
       /**
        * Create a Digest <tt>Authorization</tt> header for the given <i>realm</i>
        * and <i>state</i> to the given <i>method</i>.
  @@ -372,47 +409,47 @@
        * @param realm the basic realm to authenticate to
        * @param method the {@link HttpMethod request} requiring the digest
        * @param state a {@link HttpState} object providing {@link Credentials}
  -     * @param respHeader the header's name to store the authentication response
  -     *        in. PROXY_AUTH_RESP will force the proxy credentials to be used.
  -     * 
  +     * @param responseHeader the header's name to store the authentication
  +     *        response in. PROXY_AUTH_RESP will force the proxy credentials to
  +     *        be used.
        * @return a digest <tt>Authorization</tt> header
  -     * 
        * @throws HttpException when no matching credentials are available
        */
  -    static Header digest(String realm, HttpMethod method, HttpState state, 
  -                         String respHeader) throws HttpException {
  +    private static Header digest(String realm, HttpMethod method,
  +            HttpState state, String responseHeader) throws HttpException {
  +
           log.trace("enter Authenticator.digest(String, HttpMethod, HttpState, "
                     + "String)");
   
  -        boolean proxy = PROXY_AUTH_RESP.equals(respHeader);
  -        UsernamePasswordCredentials cred = null;
  +        boolean proxy = PROXY_AUTH_RESP.equals(responseHeader);
  +        UsernamePasswordCredentials credentials = null;
   
           try {
  -            cred = (UsernamePasswordCredentials) (proxy
  -                ? state.getProxyCredentials(realm)
  -                : state.getCredentials(realm));
  +            credentials = (UsernamePasswordCredentials) (proxy ?
  +                    state.getProxyCredentials(realm) :
  +                    state.getCredentials(realm));
           } catch (ClassCastException e) {
               throw new HttpException("UsernamePasswordCredentials required for "
                                       + "Digest authentication.");
           }
   
  -        if (null == cred) {
  +        if (credentials == null) {
               if (log.isInfoEnabled()) {
                   log.info("No credentials found for realm \"" + realm + "\", "
                            + "attempting to use default credentials.");
               }
   
               try {
  -                cred = (UsernamePasswordCredentials) (proxy
  -                    ? state.getProxyCredentials(null)
  -                    : state.getCredentials(null));
  +                credentials = (UsernamePasswordCredentials) (proxy ?
  +                        state.getProxyCredentials(null) :
  +                        state.getCredentials(null));
               } catch (ClassCastException e) {
                   throw new HttpException("UsernamePasswordCredentials required "
                                           + "for Digest authentication.");
               }
           }
   
  -        if (null == cred) {
  +        if (credentials == null) {
               throw new HttpException("No credentials available for the Digest "
                   + "authentication realm \"" + realm + "\"/");
           } else {
  @@ -422,33 +459,35 @@
               headers.put("uri", method.getPath());
               headers.put("methodname", method.getName());
   
  -            return new Header(respHeader, Authenticator.digest(cred, headers));
  +            return new Header(responseHeader, Authenticator.digest(credentials,
  +                        headers));
           }
       }
   
  +
       /**
        * Return a Digest <tt>Authorization</tt> header value for the given {@link
        * UsernamePasswordCredentials}.
  -     * @param cred Credentials to create the digest with
  +     *
  +     * @param credentials Credentials to create the digest with
        * @param headers The headers for the current request
  -     * 
        * @return a string containing the authorization header for digest
        * @throws HttpException When a recoverable error occurs
        */
  -    static String digest(UsernamePasswordCredentials cred, 
  -    			Map mapHeaders)
  -                  throws HttpException {
  +    private static String digest(UsernamePasswordCredentials cred,
  +            Map mapHeaders) throws HttpException {
  +
           log.trace("enter Authenticator.digest(UsernamePasswordCredentials, "
                     + "Map)");
   
           String digest = createDigest(cred.getUserName(), cred.getPassword(), 
                                        mapHeaders);
   
  -        return "Digest "
  -               + createDigestHeader(cred.getUserName(), 
  -               				mapHeaders, digest);
  +        return "Digest " + createDigestHeader(cred.getUserName(), mapHeaders,
  +                digest);
       }
   
  +
       /**
        * Processes the authenticate HTTP header received from the server that
        * requires Digest authentication.
  @@ -509,7 +548,6 @@
        * @param authHeader the authentication header
        * @return a map of authentication challenges or an empty map if the
        * <i>authHeader</i> is <tt>null</tt> or contains a <tt>null</tt>
value
  -     *
        * @since 2.0
        */
       private static Map parseAuthenticateHeader(Header authHeader) {
  @@ -528,45 +566,47 @@
           Map challengeMap = new Hashtable(7);
   
           final int authValueLength = authValue.length();
  -        int s = authValueLength > 0 ? 0 : -1; //start position
  -        int q1 = 0; //position of quote 1
  -        int q2 = 0; //position of quote 2
  -        int c; //position of comma
  -        int b; //position of blank
  +        int atStart = authValueLength > 0 ? 0 : -1; // start position
  +        int atQuote1 = 0; // position of quote 1
  +        int atQuote2 = 0; // position of quote 2
  +        int atComma; // position of comma
  +        int atSpace; // position of blank
   
  -        String challenge = null; //an authentication challenge
  -        String scheme = null; //the scheme from the challenge
  +        String challenge = null; // an authentication challenge
  +        String scheme = null; // the scheme from the challenge
   
           try {
  -            while (s >= 0 && s < authValueLength) {
  -                q1 = authValue.indexOf('"', s);
  -                q2 = authValue.indexOf('"', q1+1);
  -                c = authValue.indexOf(',', s);
  -
  -                //skip any commas in quotes
  -                while (c > q1 && c < q2 && c > 0) {
  -                    c = authValue.indexOf(',', c+1);
  +            while (atStart >= 0 && atStart < authValueLength) {
  +                atQuote1 = authValue.indexOf('"', atStart);
  +                atQuote2 = authValue.indexOf('"', atQuote1 + 1);
  +                atComma = authValue.indexOf(',', atStart);
  +
  +                // skip any commas in quotes
  +                while (atComma > atQuote1 && atComma < atQuote2 &&
  +                        atComma > 0) {
  +                    atComma = authValue.indexOf(',', atComma + 1);
                   }
                   
  -                //set c to be the end if there is no comma
  -                if (c < 0) {
  -                    c = authValueLength;
  +                // set atComma to be the end if there is no comma
  +                if (atComma < 0) {
  +                    atComma = authValueLength;
                   }
   
                   if (log.isDebugEnabled()) {
  -                    log.debug("s=" + s + " q1=" + q1 + " q2=" + q2 + " c=" + c);
  +                    log.debug("atStart =" + atStart + ", atQuote1 =" +
  +                            atQuote1 + ", atQuote2=" + atQuote2 + ", atComma ="
  +                            + atComma);
                   }
   
                   try {
                       //pull the current challenge and advance the start
  -                    challenge = authValue.substring(s, c).trim();
  -                    s = c+1;
  +                    challenge = authValue.substring(atStart, atComma).trim();
  +                    atStart = atComma + 1;
   
                       //find the blank and parse out the scheme
  -                    b = challenge.indexOf(' ');
  -                    scheme = (b > 0) 
  -                        ? challenge.substring(0, b).trim()
  -                        : challenge;
  +                    atSpace = challenge.indexOf(' ');
  +                    scheme = (atSpace > 0) ?
  +                        challenge.substring(0, atSpace).trim() : challenge;
   
                       //store the challenge keyed on the scheme
                       challengeMap.put(scheme.toLowerCase(), challenge);
  @@ -575,15 +615,14 @@
                       }
   
                   } catch (StringIndexOutOfBoundsException e) {
  -                    log.warn("Parsing authorization challenge'" + 
  -                            challenge + "' failed", e);
  +                    log.warn("Parsing authorization challenge'" + challenge +
  +                            "' failed", e);
                   }
  -
  -            }//end of while
  +            } // end of while
               
           } catch (StringIndexOutOfBoundsException e) {
  -            log.warn("Parsing authorization header value'" + 
  -                    authValue + "' failed", e);
  +            log.warn("Parsing authorization header value'" + authValue +
  +                    "' failed", e);
           }
   
           return challengeMap;
  @@ -600,34 +639,31 @@
        * @param authenticateHeader the header the web server created to challenge
        *        the credentials
        * @param state the http state object providing {@link Credentials}
  -     * @param respHeader the response header to add (e.g. proxy or standard)
  -     * 
  +     * @param responseHeader the response header to add (e.g. proxy or standard)
        * @return true if a response header was added
  -     * 
        * @throws HttpException when an error occurs parsing the challenge
        * @throws UnsupportedOperationException when the given challenge type is
        *         not supported
  -     * 
        * @see #basic
        * @see #digest
        * @see HttpMethod#addRequestHeader
        */
       private static boolean authenticate(HttpMethod method, HttpState state, 
  -            Header authenticateHeader, String respHeader)
  -    throws HttpException, UnsupportedOperationException {
  +            Header authenticateHeader, String responseHeader)
  +        throws HttpException, UnsupportedOperationException {
   
           log.trace("enter Authenticator.authenticate(HttpMethod, HttpState, "
                     + "Header, String)");
   
  -        //check the preemptive policy
  -        //TODO: this needs to be a service from some configuration class
  -        String preemptiveDefault = System.getProperties()
  -                                      .getProperty(PREEMPTIVE_PROPERTY, 
  -                                                   PREEMPTIVE_DEFAULT);
  +        // check the preemptive policy
  +        // TODO: this needs to be a service from some configuration class
  +        String preemptiveDefault =
  +            System.getProperties().getProperty(PREEMPTIVE_PROPERTY,
  +                    PREEMPTIVE_DEFAULT);
           preemptiveDefault = preemptiveDefault.trim().toLowerCase();
   
  -        if (!(preemptiveDefault.equals("true") 
  -            || preemptiveDefault.equals("false"))) { //property problem
  +        if (!(preemptiveDefault.equals("true")
  +                    || preemptiveDefault.equals("false"))) { // property problem
               log.warn("Configuration property " + PREEMPTIVE_PROPERTY
                        + " must be either true or false.  Using default: "
                        + PREEMPTIVE_DEFAULT);
  @@ -643,63 +679,63 @@
   
                   try {
                       Header requestHeader = Authenticator.basic(null, state, 
  -                                                               respHeader);
  +                                                               responseHeader);
                       method.addRequestHeader(requestHeader);
  -
                       return true;
                   } catch (HttpException httpe) {
                       if (log.isDebugEnabled()) {
  -                        log.debug("No default credentials to preemptively"
  -                            + " send");
  +                        log.debug(
  +                                "No default credentials to preemptively send");
                       }
  -
                       return false;
                   }
  -            } else { //no challenge and no default creds so do nothing
  -                return false;
               }
  +            // else { // no challenge and no default credentials so do nothing
  +            return false;
           }
   
  -        //parse the authenticate header
  +        // parse the authenticate header
           Map challengeMap = parseAuthenticateHeader(authenticateHeader);
   
  -        //determine the most secure request header to add
  +        // determine the most secure request header to add
           Header requestHeader = null;
           if (challengeMap.containsKey("ntlm")) {
               String challenge = (String) challengeMap.get("ntlm");
  -			requestHeader = Authenticator.ntlm(challenge, method, state, respHeader);
  +            requestHeader = Authenticator.ntlm(challenge, method, state,
  +                    responseHeader);
           } else if (challengeMap.containsKey("digest")) {
               String challenge = (String) challengeMap.get("digest");
               String realm = parseRealmFromChallenge(challenge);
  -            requestHeader = Authenticator.digest(realm, method, state, respHeader);
  +            requestHeader = Authenticator.digest(realm, method, state,
  +                    responseHeader);
           } else if (challengeMap.containsKey("basic")) {
               String challenge = (String) challengeMap.get("basic");
               String realm = parseRealmFromChallenge(challenge);
  -            requestHeader = Authenticator.basic(realm, state, respHeader);
  +            requestHeader = Authenticator.basic(realm, state, responseHeader);
           } else if (challengeMap.size() == 0) {
               throw new HttpException("No authentication scheme found in '"
                       + authenticateHeader + "'");
           } else {
  -            throw new UnsupportedOperationException("Requested authentication "
  -                    + "scheme " + challengeMap.keySet() + " is unsupported");
  +            throw new UnsupportedOperationException(
  +                    "Requested authentication scheme " + challengeMap.keySet()
  +                    + " is unsupported");
           }
   
  -        //Add the header if it has been created and return true 
  +        // Add the header if it has been created and return true 
           if (requestHeader != null) { // add the header
               method.addRequestHeader(requestHeader);
               return true;
  -        } else { // don't add the header
  -            return false;
           }
  +        // else { // don't add the header
  +        return false;
       }
   
  +
       /**
        * Creates a random cnonce value based on the current time.
        * 
        * @return The cnonce value as String.
  -     * 
        * @throws HttpException if MD5 algorithm is not supported.
  -     * 
        * @todo + Add createCnonce() method
        */
       private static String createCnonce() throws HttpException {
  @@ -724,34 +760,33 @@
           return cnonce;
       }
   
  +
       /**
        * Creates the header information that must be specified after the "Digest"
        * string in the HTTP Authorization header (digest-response in RFC2617).
        * 
        * @param uname Username
  -     * @param mapCreds Map containing header information (uri, realm,
  +     * @param mapCredentials Map containing header information (uri, realm,
        *        nonce, nc, cnonce, opaque, qop).
        * @param digest The response tag's value as String.
  -     * 
        * @return The digest-response as String.
  -     * 
        * @todo + Add createDigestHeader() method 
        */
  -    private static String createDigestHeader(String uname, 
  -    					Map mapCreds, 
  -						String digest) {
  +    private static String createDigestHeader(String uname, Map mapCredentials,
  +            String digest) {
  +
           log.trace("enter Authenticator.createDigestHeader(String, Map, "
               + "String)");
   
           StringBuffer sb = new StringBuffer();
  -        String uri = removeQuotes((String) mapCreds.get("uri"));
  -        String realm = removeQuotes((String) mapCreds.get("realm"));
  -        String nonce = removeQuotes((String) mapCreds.get("nonce"));
  -        String nc = removeQuotes((String) mapCreds.get("nc"));
  -        String cnonce = removeQuotes((String) mapCreds.get("cnonce"));
  -        String opaque = removeQuotes((String) mapCreds.get("opaque"));
  +        String uri = removeQuotes((String) mapCredentials.get("uri"));
  +        String realm = removeQuotes((String) mapCredentials.get("realm"));
  +        String nonce = removeQuotes((String) mapCredentials.get("nonce"));
  +        String nc = removeQuotes((String) mapCredentials.get("nc"));
  +        String cnonce = removeQuotes((String) mapCredentials.get("cnonce"));
  +        String opaque = removeQuotes((String) mapCredentials.get("opaque"));
           String response = digest;
  -        String qop = removeQuotes((String) mapCreds.get("qop"));
  +        String qop = removeQuotes((String) mapCredentials.get("qop"));
   
           if (qop != null) {
               qop = "auth"; //we only support auth
  @@ -762,36 +797,31 @@
           sb.append("username=\"" + uname + "\"")
             .append(", realm=\"" + realm + "\"")
             .append(", nonce=\"" + nonce + "\"").append(", uri=\"" + uri + "\"")
  -          .append(((qop == null)            ? "" : ", qop=\"" + qop + "\""))
  +          .append(((qop == null) ? "" : ", qop=\"" + qop + "\""))
             .append(", algorithm=\"" + algorithm + "\"")
  -          .append(((qop == null)            ? "" : ", nc=" + nc))
  -          .append(((qop == null)            ? "" : ", cnonce=\"" + cnonce
  -                      + "\"")).append(", response=\"" + response + "\"")
  -          .append((opaque == null)           ? "" : ", opaque=\"" + opaque
  -                  + "\"");
  +          .append(((qop == null) ? "" : ", nc=" + nc))
  +          .append(((qop == null) ? "" : ", cnonce=\"" + cnonce + "\""))
  +          .append(", response=\"" + response + "\"")
  +          .append((opaque == null) ? "" : ", opaque=\"" + opaque + "\"");
   
           return sb.toString();
       }
   
  +
       /**
        * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long 
        * <CODE>String</CODE> according to RFC 2617.
        * 
        * @param binaryData array containing the digest
  -     * 
        * @return encoded MD5, or <CODE>null</CODE> if encoding failed
  -     * 
        * @todo + Add encode() method 
        */
       private static String encode(byte[] binaryData) {
           log.trace("enter Authenticator.encode(byte[])");
   
  -        if (binaryData.length != 16) {
  -            return null;
  -        }
  +        if (binaryData.length != 16) return null;
   
           char[] buffer = new char[32];
  -
           for (int i = 0; i < 16; i++) {
               int low = (int) (binaryData[i] & 0x0f);
               int high = (int) ((binaryData[i] & 0xf0) >> 4);
  @@ -802,28 +832,28 @@
           return new String(buffer);
       }
   
  +
       /**
        * Parse the realm from the authentication challenge
        * 
        * @param challenge the authentication challenge
  -     * 
        * @return the realm
  -     * 
        * @throws HttpException when the realm can't be parsed
        */
       private static String parseRealmFromChallenge(String challenge)
  -                                           throws HttpException {
  +        throws HttpException {
  +
           // FIXME: Note that this won't work if there is more than one realm
           // within the challenge
           try {
               StringTokenizer strtok = new StringTokenizer(challenge, "=");
               String realmName = strtok.nextToken().trim();
               String realm = strtok.nextToken().trim();
  -            int firstq = realm.indexOf('"');
  -            int lastq = realm.lastIndexOf('"');
  +            int atFirst = realm.indexOf('"');
  +            int atLast = realm.lastIndexOf('"');
   
  -            if ((firstq + 1) < lastq) {
  -                realm = realm.substring(firstq + 1, lastq);
  +            if ((atFirst + 1) < atLast) {
  +                realm = realm.substring(atFirst + 1, atLast);
               }
   
               if (log.isDebugEnabled()) {
  @@ -838,6 +868,7 @@
           }
       }
   
  +
       /**
        * Takes an entry of <CODE>"xxx=yyy"</CODE> format, partitions into a key
        * and a value (key will be the left side, value will be the right side of
  @@ -846,20 +877,20 @@
        * @param token the entry to be processed
        * @param tokens the <CODE>java.util.Map</CODE> into which the processed
        *        entry is placed (only if it has <CODE>"xxx=yyy"</CODE> format).
  -     * 
        * @todo + Add processDigestToken() method 
        */
       private static void processDigestToken(String token, Map tokens) {
           log.trace("enter Authenticator.processDigestToken(String, Map)");
   
  -        int eqpos = token.indexOf("=");
  +        int atEqual = token.indexOf("=");
   
  -        if ((eqpos > 0) && (eqpos < (token.length() - 1))) {
  -            tokens.put(token.substring(0, eqpos).trim(), 
  -                   token.substring(eqpos + 1).trim());
  +        if ((atEqual > 0) && (atEqual < (token.length() - 1))) {
  +            tokens.put(token.substring(0, atEqual).trim(),
  +                    token.substring(atEqual + 1).trim());
           }
       }
   
  +
       /**
        * Takes a <CODE>String</CODE> and cuts its prefix until the first double
        * quotation mark and its suffix from the last double quotation mark (and
  @@ -867,25 +898,21 @@
        * 
        * @param str the <CODE>String</CODE> from which the prefix and suffix
is
        *        to be cut.
  -     * 
        * @return the stumped <CODE>String</CODE> if the format of
  -     *         <CODE>str</CODE> is <CODE>""</CODE>. Otherwise the
return value
  +     *         <CODE>str</CODE> is <CODE>""</CODE>; Otherwise the
return value
        *         is same as <CODE>str</CODE>
        */
       private static String removeQuotes(String str) {
           log.trace("enter Authenticator.removeQuotes(String)");
   
  -        if (str == null) {
  -            return null;
  -        }
  +        if (str == null) return null;
   
  -        int fqpos = str.indexOf("\"") + 1;
  -        int lqpos = str.lastIndexOf("\"");
  +        int atFirst = str.indexOf("\"") + 1;
  +        int atLast = str.lastIndexOf("\"");
   
  -        if ((fqpos > 0) && (lqpos > fqpos)) {
  -            return str.substring(fqpos, lqpos);
  -        } else {
  -            return str;
  -        }
  +        return (atFirst > 0 && atLast > atFirst) ?
  +            str.substring(atFirst, atLast) : str;
       }
  +
   }
  +
  
  
  

--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message