Jersey客户端API - 身份验证

时间:2011-07-21 10:16:43

标签: authentication client jersey

我正在使用Jersey客户端API将SOAP请求提交给JAX-WS Web服务。默认情况下,Jersey在某种程度上使用我的Windows Nt凭据进行身份验证时进行身份验证。任何人都可以解释泽西在代码中的位置吗?它可以被覆盖吗?

我尝试过使用HTTPBasicAuthFilter并在客户端上添加过滤器。我也尝试将我的凭据添加到WebResoruce queryParams字段中,但都没有被提取。

7 个答案:

答案 0 :(得分:71)

首先,我按照泽西用户指南

中的说明开始工作
Authenticator.setDefault (authinstance);

但是我不喜欢这个,因为它依赖于设置全局身份验证器。经过一番研究后,我发现泽西岛有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)

答案 1 :(得分:32)

泽西岛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 Authentication Support

答案 2 :(得分:12)

泽西岛用户指南中有一小部分关于Client authentication。我建议你按照它的建议尝试使用Apache HTTP Client而不是HttpURLConnection,因为它可以更好地支持你想要做的任何事情。

答案 3 :(得分:2)

添加此答案,因为我一直在寻找在2.x中不再相关的旧版Jersey的答案。

对于泽西2来说,有几种方法。 看看:

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

这是一个适合我的人(最简单的基本身份验证恕我直言)。

    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) );

答案 4 :(得分:1)

如果您正在测试Dropwizard应用程序(可能它适合任何REST服务),您可以使用它作为示例: https://github.com/dropwizard/dropwizard/blob/v0.8.1/dropwizard-auth/src/test/java/io/dropwizard/auth/basic/BasicAuthProviderTest.java

答案 5 :(得分: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 Class

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;
    }

}

答案 6 :(得分:0)

是的,对于jersey 2.x,您可以使用基本身份验证(抢先模式)对每个请求进行身份验证:

 client.register(HttpAuthenticationFeature.basic(userName, password));
 // rest invocation code ..
相关问题