Jersey 客户端 API - 身份验证

发布于 2024-11-25 04:31:48 字数 230 浏览 1 评论 0原文

我正在使用 Jersey 客户端 API 向 JAX-WS Web 服务提交 SOAP 请求。默认情况下,Jersey 在受到质询时以某种方式使用我的 Windows Nt 凭据进行身份验证。谁能解释一下 Jersey 在代码中的位置?它可以被覆盖吗?

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

I'm using the Jersey client API to submit SOAP requests to a JAX-WS webservice. By default Jersey is somehow using my Windows Nt credentials for authentication when challenged. Can anyone explain where Jersey does this in the code? And can it be overriden?

I have tried using HTTPBasicAuthFilter and adding as a filter on the Client. I have also tried adding my credentials to the WebResoruce queryParams field however neither are being picked up.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

天邊彩虹 2024-12-02 04:31:48

起初,我按照泽西岛用户指南中的记录进行了这项工作

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)

At first I got this working as documented in the Jersey User guide

Authenticator.setDefault (authinstance);

However I did not like this as it relied on setting a global authenticator. After some research I discovered that Jersey has a HTTPBasicAuthFilter which is even easier to use.

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

See:
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)

给我一枪 2024-12-02 04:31:48

Jersey 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认证支持

Jersey 2.x:

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

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

Client client = ClientBuilder.newClient(clientConfig);

Reference: 5.9.1. Http Authentication Support

水中月 2024-12-02 04:31:48

Jersey 用户指南中有一小节介绍客户端身份验证。我建议您遵循其建议并尝试使用 Apache HTTP Client 而不是 HttpURLConnection,因为它对您想做的任何事情都有更好的支持。

There's a small section in the Jersey User guide about Client authentication. I'd recommend you follow its advice and try using Apache HTTP Client instead of HttpURLConnection, as it has much better support for just about anything you'd want to do.

む无字情书 2024-12-02 04:31:48

添加这个答案是因为我不断寻找旧版本 Jersey 的答案,这些版本在 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) );

Adding this answer as I keep finding answers for older versions of Jersey that are no longer relevant in 2.x.

For Jersey 2 there are several ways.
Take a look at:

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

Here is the one that is working for me (simplest basic auth IMHO).

    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) );
时光病人 2024-12-02 04:31:48

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

If you are testing a Dropwizard application (maybe it suits any REST service), you can use this as an example:
https://github.com/dropwizard/dropwizard/blob/v0.8.1/dropwizard-auth/src/test/java/io/dropwizard/auth/basic/BasicAuthProviderTest.java

放飞的风筝 2024-12-02 04:31:48

请找到以下没有 SSL 的工作代码

,我正在使用 put request ,如果需要 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":"[email protected]"}





            Employee employee = new Employee("Viquar", "Khan", "[email protected]");


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

}

Please find following working code without SSL

I am using put request , if need post/get just change it.

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":"[email protected]"}





            Employee employee = new Employee("Viquar", "Khan", "[email protected]");


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

}
北城孤痞 2024-12-02 04:31:48

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

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

Yes for jersey 2.x you can do this to authenticate each request with basic auth (preemptive mode):

 client.register(HttpAuthenticationFeature.basic(userName, password));
 // rest invocation code ..
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文