📄 digestscheme.java
字号:
/* * $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 $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * 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.commons.httpclient.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;/** * <p> * Digest authentication scheme as defined in RFC 2617. * Both MD5 (default) and MD5-sess are supported. * Currently only qop=auth or no qop is supported. qop=auth-int * is unsupported. If auth and auth-int are provided, auth is * used. * </p> * <p> * Credential charset is configured via the * {@link org.apache.commons.httpclient.params.HttpMethodParams#CREDENTIAL_CHARSET credential * charset} parameter. Since the digest username is included as clear text in the generated * Authentication header, the charset of the username must be compatible with the * {@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 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> */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. * * @see #encode(byte[]) */ private static final char[] HEXADECIMAL = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** Whether the digest authentication process is complete */ private boolean complete; //TODO: supply a real nonce-count, currently a server will interprete a repeated request as a replay private static final String NC = "00000001"; //nonce-count is always 1 private static final int QOP_MISSING = 0; private static final int QOP_AUTH_INT = 1; private static final int QOP_AUTH = 2; private int qopVariant = QOP_MISSING; private String cnonce; private final ParameterFormatter formatter; /** * Default constructor for the digest authetication scheme. * * @since 3.0 */ 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); } /** * Processes the Digest challenge. * * @param challenge the challenge string * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @since 3.0 */ public void processChallenge(final String challenge) throws MalformedChallengeException { super.processChallenge(challenge); if (getParameter("realm") == null) { throw new MalformedChallengeException("missing realm in challange"); } if (getParameter("nonce") == null) { throw new MalformedChallengeException("missing nonce in challange"); } boolean unsupportedQop = false; // qop parsing String qop = getParameter("qop"); if (qop != null) { StringTokenizer tok = new StringTokenizer(qop,","); while (tok.hasMoreTokens()) { String variant = tok.nextToken().trim(); if (variant.equals("auth")) { qopVariant = QOP_AUTH; break; //that's our favourite, because auth-int is unsupported } else if (variant.equals("auth-int")) { qopVariant = QOP_AUTH_INT; } else { unsupportedQop = true; LOG.warn("Unsupported qop detected: "+ variant); } } } if (unsupportedQop && (qopVariant == QOP_MISSING)) { throw new MalformedChallengeException("None of the qop methods is supported"); } cnonce = createCnonce(); this.complete = true; } /** * Tests if the Digest authentication process has been completed. * * @return <tt>true</tt> if Digest authorization has been processed, * <tt>false</tt> otherwise. * * @since 3.0 */ public boolean isComplete() { String s = getParameter("stale"); if ("true".equalsIgnoreCase(s)) { return false; } else { return this.complete; } } /** * Returns textual designation of the digest authentication scheme. * * @return <code>digest</code> */ public String getSchemeName() { return "digest"; } /** * Returns <tt>false</tt>. Digest authentication scheme is request based. * * @return <tt>false</tt>. * * @since 3.0 */ public boolean isConnectionBased() { return false; } /** * 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 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 * are not valid or not applicable for this authentication scheme
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -