Jersey-client基本身份验证

时间:2015-06-16 12:22:41

标签: java http basic-authentication jersey-client

我试图通过HTTPS发送包含HTTP标头中基本身份验证的REST请求,问题似乎是身份验证没有插入标头。

    HttpAuthenticationFeature feature = HttpAuthenticationFeature
            .basicBuilder().build();

    Client client = ClientBuilder.newBuilder().sslContext(getSSLContext())
            .hostnameVerifier(getHostNameVerifier()).build();
    client.register(feature);
    client.register(new LoggingFilter());
    try
    {
        String entity = client
                .target(url)
                .request(MediaType.APPLICATION_XML)
                .property(
                        HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_USERNAME,
                        "username")
                .property(
                        HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_PASSWORD,
                        "password").get(String.class);

        System.out.println(entity);
    } catch (WebApplicationException e)
    {
        ByteArrayInputStream in = (ByteArrayInputStream) e.getResponse()
                .getEntity();
        int n = in.available();
        byte[] bytes = new byte[n];
        in.read(bytes, 0, n);
        String entity = new String(bytes, StandardCharsets.UTF_8);
        System.out.println(entity);
    }

日志说的是什么:

Jun 16, 2015 2:06:53 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Sending client request on thread JavaFX Application Thread
1 > GET https://url
1 > Accept: application/xml

Jun 16, 2015 2:06:53 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 2 * Client response received on thread JavaFX Application Thread
2 < 403
2 < Connection: Keep-Alive
2 < Content-Length: 240
2 < Content-Type: text/html; charset=iso-8859-1
2 < Date: Tue, 16 Jun 2015 12:06:53 GMT
2 < Keep-Alive: timeout=15, max=100

结果代码只是403 Forbidden。

如果删除行client.register(feature);,则行2 < WWW-authenticate: basic realm="/"会添加到日志末尾,结果代码为401 Authorization Requried而不是403.

在FireFox中使用HTTP Requester时,REST请求正常工作。

我想我在某个地方错过了什么?

1 个答案:

答案 0 :(得分:2)

如果你需要使用Pre-Jersey 2.X,这很难,很明显。如果你需要进行HTTPS(SSL)基本身份验证,那么使用Jersey 2.X以后它会变得非常容易。
这些说明使用的是Jersey 2.25.1:

  1. 如果您使用的是self-signed certificate,则在使用有效登录进行身份验证后,必须先从浏览器中的HTTPS页面下载.cer / .crt / .cet文件。 GuideSO Answer
  2. 然后在Jersey 2.X中使用不同的Feature(javax.ws.rs.core)实现来输入所有这些信息。
  3. 使用SSLContext构建WebTarget和Client的示例代码:

    HttpAuthenticationFeature auth = HttpAuthenticationFeature.basic("admin", password);
    SslConfigurator config = SslConfigurator.newInstance()
            .keyStoreFile("C:\Program Files\Java\jdk\jre\lib\security\cacerts")
            .keyPassword("changeit");
    SSLContext sslContext = config.createSSLContext();
    Client client = ClientBuilder.newBuilder()
            .sslContext(sslContext)
            .register(SseFeature.class)
            .register(auth)
            .build();
    WebTarget target = client.target(sourcePath);