Spnego auth不适用于响应代码驱动的http客户端

时间:2013-05-22 04:56:13

标签: http kerberos spnego

我正在尝试编写一个连接到启用了kerberos的tomcat的http客户端(使用浏览器测试是正确的)。它首先获得响应代码(将是401)并继续其工作。

代码是

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;

public class SampleHTTP2 {

    static final String kuser = "correctusername"; // your account name
    static final String kpass = "correctpassword"; // your password for the account

    static class MyAuthenticator extends Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            //System.out.println("I am reaching here");
            // I haven't checked getRequestingScheme() here, since for NTLM
            // and Negotiate, the username and password are all the same.
            System.err.println("Feeding username and password for "
               + getRequestingScheme());
            return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
    }

    public static void main(String[] args) throws Exception {

        URL url = new URL("http://mycompname:6008/examples/");
        HttpURLConnection h1 = (HttpURLConnection) url.openConnection();

        int rescode = h1.getResponseCode();

        System.out.println(rescode);
        System.setProperty("sun.security.krb5.debug", "true");
        System.setProperty("java.security.auth.login.config", "C:\\login2.conf");
        System.setProperty("javax.security.auth.useSubjectCredsOnly","false");

        System.setProperty("java.security.krb5.conf", "C:\\krb5.ini");
        if(rescode == 401){     
            Authenticator.setDefault(new MyAuthenticator());

            URL url2 = new URL("http://mycompname/examples/");
            URLConnection h2 = url2.openConnection();
            InputStream ins2 = h2.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(ins2));
            String str;
            while((str = reader.readLine()) != null)
                System.out.println(str);
        }
    }
}

现在我评论这一行: -

 int rescode = h1.getResponseCode();

并输入if(true)而不是if(rescode == 401),它可以工作。

我不确定出了什么问题。 getResponseCode()在内部调用getinputStream,因此我使用了单独的url连接。即使它仍然不起作用

P.S - 服务器设置完好,Authenticator类也正确。

0 个答案:

没有答案