使用Java中的Kerberos keytab进行HTTP调用

时间:2019-11-25 06:33:59

标签: java http authentication kerberos spnego

我正在尝试向受Kerberos身份验证保护的HTTP端点发出GET请求。我能够使用密钥表成功初始化LoginContext,并且可以看到KerberosTicket正在生成并成功分配给Subject,但是由于某些原因,我的HTTP请求仍然存在出现401错误。我怀疑票证本身没有附加到HTTP请求中,但是我不确定如何正确启用它。

作为参考,这是我正在运行的代码。我正在使用Krb5LoginModule:

        String keyTab = "~/kerberos.keytab";
        String principal = "myself@WEBSITE.COM";
        Subject subject = null;
        try {
            LoginContext context = new LoginContext("", new Subject(), null,
                    new Configuration() {
                        @Override
                        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
                            Map<String, String> options = new HashMap<String, String>();
                            options.put("useKeyTab", "true");
                            options.put("storeKey", "true");
                            options.put("doNotPrompt", "false");
                            options.put("useTicketCache", "true");
                            options.put("isInitiator", "true");
                            options.put("debug", "true");
                            options.put("keyTab", keyTab);
                            options.put("principal", principal);

                            return new AppConfigurationEntry[]{
                                    new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                                            options)};
                        }
                    });
            context.login(); // Completes successfully. No LoginException thrown.
            subject = context.getSubject();
        }
        catch (LoginException e)
        {
            e.printStackTrace();
            return null;
        }

        String conn = Subject.doAs(subject, new PrivilegedExceptionAction<String>() {

            @Override
            public String run() {
                    URL url = new URL("http://kerberosexample.com");
                    con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("GET");

                    if (con != null) {
                        int status = con.getResponseCode(); // Returns as 401 Unauthenticated.

                        // If status is 200, process response body and return as a String.
                    }
            }
        });

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

指向正确的krb5.conf。应该做的工作。 类似于System.setProperty("java.security.krb5.conf", "krb5.conf");