使用httpclient \ kerberos以编程方式而不是提示方式设置用户名

时间:2012-06-06 22:34:19

标签: java linux authentication sharepoint-2010 kerberos

我有一个linux \ java6客户端,它将使用KERBEROS对sharepoint2010进行身份验证,然后使用Apache Commons HttpClient 4.2发送HTTP REST Web服务

如果我在连接客户端之前从命令行"kinit myuser@mydomain"运行,则可以顺畅运行。

我的问题是,如果我不运行kinit,我会收到提示输入用户名。

如何在不提示用户名的情况下以编程方式进行身份验证,而无需运行命令行程序?

(我创建了keytab并在login.conf中定义了它,因此负责密码提示而不是用户promt)

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

    System.setProperty("java.security.auth.login.config", "login.conf");
    System.setProperty("java.security.krb5.conf", "krb5.conf");
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly","false");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());

        Credentials use_jaas_creds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(null, -1, null),
                use_jaas_creds);

        HttpUriRequest request = new HttpGet("http://kerberoshost/");
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println("----------------------------------------");
        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }
        System.out.println("----------------------------------------");

        // This ensures the connection gets released back to the manager
        EntityUtils.consume(entity);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

1 个答案:

答案 0 :(得分:3)

除了keytab文件之外,您还必须提供主体名称以获得完全透明的客户端Kerberos身份验证(kinit):

 client {
   com.sun.security.auth.module.Krb5LoginModule required
     useKeyTab=true
     storeKey=true
     keyTab=/path/to/userKeytab
     principal="userName";
 };