【问题标题】:Jersey Client API - authenticationJersey 客户端 API - 身份验证
【发布时间】:2020-07-30 17:10:17
【问题描述】:

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

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

【问题讨论】:

    标签: authentication client jersey


    【解决方案1】:

    起初,我按照 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。非常优雅地为应用程序增加了安全性。
    • 请参阅下面的 Jersey 2.x 答案
    • 我这样做了:HTTPBasicAuthFilter feature = new HTTPBasicAuthFilter(restUsername,restPassword); client.addFilter(feature);,但由于某些未知原因,我不断获得null 的功能。为什么会发生,知道吗?
    【解决方案2】:

    球衣 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

    【讨论】:

    • 或:响应 response = client.target("localhost:8080/rest/homer/contact").request() .property(HTTP_AUTHENTICATION_BASIC_USERNAME, "homer") .property(HTTP_AUTHENTICATION_BASIC_PASSWORD, "p1swd745").get();
    • 我也这样做了!!但仍然没有身份验证有效!。
    • 这对我不起作用,我仍然收到 403 回复。我没有使用 HTTPS,因为我没有证书并且正在尝试在本地进行测试。这个基本身份验证是否必须使用 HTTPS?有没有办法强制它在纯 HTTP 上工作?我不在乎它不是 SSL。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 这对我很有用。谢谢。
      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

        请在没有 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":"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;
            }
        
        }
        

        【讨论】:

          【解决方案7】:

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

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

          【讨论】:

            猜你喜欢
            • 2012-01-23
            • 1970-01-01
            • 1970-01-01
            • 2018-06-21
            • 2018-01-09
            • 2016-01-23
            • 1970-01-01
            • 1970-01-01
            • 2016-07-09
            相关资源
            最近更新 更多