基本认证在Java中的HTTPS实现

4

我已经成功实现了HTTPS页面的调用,并且HTTP基本认证也能正常使用,但我无法在HTTPS连接上运行基本认证功能。

我附上了代码示例,但它不起作用。我一直得到一个403错误。我已经检查了用户名和密码,在Firefox浏览器上使用RESTClient插件测试时也是成功的。

希望能得到任何帮助。谢谢。

   private static void getAPITest() throws MalformedURLException, IOException 
{        
    try {


    System.setProperty("javax.net.ssl.trustStore","/home/USER/CERTS/myTrustStore");
    System.setProperty("javax.net.ssl.trustStorePassword", "PASSWORD");


     Authenticator myAuth = new Authenticator() 
        {
            @Override
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("USERNAME", "PASSWORD".toCharArray());
            }
        };

        Authenticator.setDefault(myAuth);


        String httpsURL = "https://someurlandapi.com";
        URL myurl = new URL(httpsURL);
        HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
        //con.setRequestProperty("Authorization", "Basic " + authString);
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestMethod("POST");            

        InputStream ins = con.getInputStream();
        InputStreamReader isr = new InputStreamReader(ins);
        BufferedReader in = new BufferedReader(isr);

        String inputLine;

        while ((inputLine = in.readLine()) != null)
        {
          System.out.println(inputLine);
        }

        ins.close();
        in.close();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
2个回答

3
原来在基本元素前面不应该有空格:
con.setRequestProperty("Authorization", "Basic " + authStringEnc);

and it needed:

conn.setRequestProperty("User-Agent", "Mozilla/5");

如果您正在创建自己的信任库,请注意需要添加站点/网址的SSL证书链。在Firefox中,您可以单击锁形图标 > 更多信息 > 安全 > 查看证书。从那里,您可以选择带有链式导出的证书并使用keytool将其添加到您的信任库中:

keytool -import -file websitecertificate.pem -alias websitecert -keystore myTrustStore

2

我认为 PasswordAuthentication 并没有做到你想要的。但是基本身份验证非常容易自己处理。如果你使用 Java8,只需使用 Base64.getEncoder().encodeToString(("USERNAME" + ":" + "PASSWORD").getBytes())。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接