Jersey客户端API - 认证

49

我正在使用Jersey客户端API向JAX-WS Web服务提交SOAP请求。默认情况下,当受到挑战时,Jersey会以某种方式使用我的Windows NT凭据进行身份验证。有人可以解释一下Jersey在代码中是如何实现这个功能的吗?是否可以覆盖它?

我尝试过使用HTTPBasicAuthFilter并将其作为过滤器添加到Client中。我也尝试将我的凭据添加到WebResoruce queryParams字段中,但都未被拾取。

7个回答

73

一开始我按照Jersey用户指南中的文档操作,成功了。

Authenticator.setDefault (authinstance);

然而,我不喜欢这种方法,因为它依赖于设置全局的身份验证器。经过一些研究,我发现Jersey有一个HTTPBasicAuthFilter,使用起来甚至更加容易。

Client c = Client.create();
c.addFilter(new HTTPBasicAuthFilter(user, password));

请查看: https://jersey.github.io/nonav/apidocs/1.10/jersey/com/sun/jersey/api/client/filter/HTTPBasicAuthFilter.html https://jersey.github.io/nonav/apidocs/1.10/jersey/com/sun/jersey/api/client/filter/Filterable.html#addFilter(com.sun.jersey.api.client.filter.ClientFilter)


这正是我一直在寻找的。我将其添加到我们的客户端,并在服务器端使用了Spring Security。非常优雅地为应用程序添加了安全性。 - bh5k
请参见下面的答案,了解Jersey 2.x的相关内容。 - Dejell
我执行了以下代码:HTTPBasicAuthFilter feature = new HTTPBasicAuthFilter(restUsername,restPassword); client.addFilter(feature); 但是出现了一个未知的问题,feature 始终为 null。你有任何想法吗? - HitchHiker

37

新泽西 2.x:

HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
    .nonPreemptive()
    .credentials("user", "password")
    .build();

ClientConfig clientConfig = new ClientConfig();
clientConfig.register(feature) ;

Client client = ClientBuilder.newClient(clientConfig);

参考:5.9.1. Http身份验证支持


4
或者:响应 response = client.target("http://localhost:8080/rest/homer/contact").request() .property(HTTP_AUTHENTICATION_BASIC_USERNAME, "homer") .property(HTTP_AUTHENTICATION_BASIC_PASSWORD, "p1swd745").get(); - Dejell
我也做了同样的事情!!但是身份验证仍然无法工作! - learner
这对我不起作用,我仍然收到403响应。我没有使用HTTPS,因为我没有证书,并且正在尝试在本地测试。这个基本身份验证是否必须使用HTTPS?有没有办法强制它在纯HTTP上工作?我不关心它是否SSL加密。 - Alex Worden

11

Jersey用户指南中有一个关于客户端认证的小节。我建议你遵循它的建议,尝试使用Apache HTTP Client代替HttpURLConnection,因为它对于几乎任何你想做的事情都有更好的支持。


6

我添加这个答案是因为我一直在找适用于旧版本Jersey的答案,但在2.x中已经不再适用。

对于Jersey 2,有几种方法。 请查看:

org.glassfish.jersey.client.authentication.HttpAuthenticationFeature的JavaDoc

以下是我正在使用的最简单的基本身份验证方法。

    ClientConfig config = new ClientConfig();

    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password");

    Client client = ClientBuilder.newClient(config);
    client.register(feature);

    WebTarget webTarget = client.target("http://api.asite.com/api").path("v1/reports/list");
    Invocation.Builder invocationBuilder =  webTarget.request(MediaType.TEXT_PLAIN_TYPE);

    Response response = invocationBuilder.get();

    System.out.println( response.getStatus() );
    System.out.println( response.readEntity(String.class) );

这对我很有用。谢谢。 - hreinn

1

0
请查看以下没有SSL的工作代码:
我正在使用put请求,如果需要post/get,请更改它。

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javacodegeeks.enterprise.rest.jersey</groupId>
    <artifactId>JerseyJSONExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <dependencies>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.9</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.9</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.9</version>
        </dependency>

    </dependencies>

</project>

Java类
package com.rest.jersey.jerseyclient;

import com.rest.jersey.dto.Employee;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClient {

    public static void main(String[] args) {
        try {

            String username = "username";
            String password = "p@ssword";


            //{"userId":"12345","name ":"Viquar","surname":"Khan","email":"Vaquar.khan@gmail.com"}





            Employee employee = new Employee("Viquar", "Khan", "Vaquar.khan@gmail.com");


            ClientConfig clientConfig = new DefaultClientConfig();

            clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

            Client client = Client.create(clientConfig);
            //


                final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
                client.addFilter(authFilter);
                client.addFilter(new LoggingFilter());

            //
            WebResource webResource = client
                    .resource("http://localhost:7001/VaquarKhanWeb/employee/api/v1/informations");

              ClientResponse response = webResource.accept("application/json")
                .type("application/json").put(ClientResponse.class, employee);


            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatus());
            }

            String output = response.getEntity(String.class);

            System.out.println("Server response .... \n");
            System.out.println(output);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

POJO

package com.rest.jersey.dto;

public class Employee {

    private String name;
    private String surname;
    private String email;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "Employee [name=" + name + ", surname=" + surname + ", email=" + email + "]";
    }
    public Employee(String name, String surname, String email) {
        super();
        this.name = name;
        this.surname = surname;
        this.email = email;
    }

}

0

对于Jersey 2.x,您可以使用基本身份验证(预取模式)对每个请求进行身份验证:

 client.register(HttpAuthenticationFeature.basic(userName, password));
 // rest invocation code ..

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