使用URLConnection进行摘要式身份验证

时间:2010-11-25 16:06:58

标签: java urlconnection digest-authentication

我正在实施单点登录功能,以使用摘要式身份验证自动登录到附属的https网站。目前我的代码是

URL url = new URL(protocol, ip, port, path);
URLConnection connection = url.openConnection(Proxy.NO_PROXY);
connection.connect();

if (connection != null && connection.getHeaderFields() != null) {
    if (connection.getHeaderFields().get(AUTHENTICATE_RESPONSE_HEADER) != null) {
        Map<String, String> authenticateParameters = identifyAuthentication(connection);

        String ha1 = calculateMD5(username + ":" + authenticateParameters.get("realm") + ":" + password);
        String ha2 = calculateMD5("GET" + ":" + path);
        String response = calculateMD5(ha1 + ":" + 
            authenticateParameters.get("nonce") + ":" +
            "00000001" + ":" +
            authenticateParameters.get("qop") + ":" +
            ha2);

            String authorizationRequest = authenticateParameters.get("challenge") + " " + 
                    "username=" + username + ", " +
                    "realm=" + authenticateParameters.get("realm") + ", " +
                    "nonce=" + authenticateParameters.get("nonce") + ", " +
                    "uri=" + path + ", " +
                    "qop=" + authenticateParameters.get("qop") + ", " +
                    "nc=" + "00000001" + ", " +
                    "response=" + response + ", " +
                    "opaque=" + authenticateParameters.get("opaque");

            connection.setAllowUserInteraction(true);
            connection.addRequestProperty(AUTHENTICATION_REQUEST_PROPERTY, authorizationRequest);
            connection.getHeaderFields();
    }
}

问题是我得到了

java.lang.IllegalStateException: Already connected
    at java.net.URLConnection.addRequestProperty(URLConnection.java:1061)
    at sun.net.www.protocol.http.HttpURLConnection.addRequestProperty(HttpURLConnection.java:2016)
    at com.ibm.net.ssl.www2.protocol.https.a.addRequestProperty(a.java:49)
我猜,这是有道理的,但对我没有帮助。我如何创建一个登录请求/响应(最终获得sessionId)?

提前致谢。

1 个答案:

答案 0 :(得分:5)

连接请求标头(已经发送了请求标头)时,无法修改连接请求标头。您必须为第二个请求建立新连接。

E.g。

connection = url.openConnection(Proxy.NO_PROXY);
connection.addRequestProperty(AUTHENTICATION_REQUEST_PROPERTY, authorizationRequest);
connection.getHeaderFields();

然后,您可以从标题中获取sessionId或更确切地说cookie。

使用apache HttpClient的摘要功能可能更容易:http://hc.apache.org/httpclient-3.x/authentication.html