2011-07-21 39 views
40

Tôi đang sử dụng API ứng dụng khách của Jersey để gửi yêu cầu SOAP đến dịch vụ web JAX-WS. Theo mặc định, Jersey bằng cách nào đó sử dụng thông tin đăng nhập Windows Nt của tôi để xác thực khi được thử thách. Bất cứ ai có thể giải thích nơi Jersey làm điều này trong mã? Và nó có thể được overriden?API ứng dụng khách của Jersey - xác thực

Tôi đã thử sử dụng HTTPBasicAuthFilter và thêm làm bộ lọc trên Máy khách. Tôi cũng đã thử thêm thông tin đăng nhập của tôi vào trường WebResoruce queryParams tuy nhiên không được chọn.

Trả lời

65

Lúc đầu, tôi đã làm việc này như tài liệu trong Hướng dẫn sử dụng Jersey

Authenticator.setDefault (authinstance); 

Tuy nhiên tôi không thích điều này vì nó dựa vào thiết lập một xác thực toàn cầu. Sau một số nghiên cứu, tôi phát hiện ra rằng Jersey có HTTPBasicAuthFilter thậm chí còn dễ sử dụng hơn.

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

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

+0

Đây chính xác là những gì tôi đang tìm kiếm. Tôi đã thêm điều này vào ứng dụng khách của chúng tôi và đã sử dụng Bảo mật mùa xuân trên phần máy chủ. Làm việc rất tao nhã để tăng tính bảo mật cho ứng dụng. – bh5k

+0

Xem câu trả lời bên dưới cho Jersey 2.x – Dejell

+0

Tôi đã làm điều này: 'HTTPBasicAuthFilter feature = new HTTPBasicAuthFilter (restUsername, restPassword); client.addFilter (feature); 'nhưng đối với một số lý do không rõ tôi tiếp tục nhận được tính năng là' null'. Tại sao nó sẽ xảy ra, bất kỳ ý tưởng? – HitchHiker

12

Có một phần nhỏ trong hướng dẫn sử dụng Jersey về Client authentication. Tôi khuyên bạn nên làm theo lời khuyên của nó và thử sử dụng Apache HTTP Client thay vì HttpURLConnection, vì nó có hỗ trợ tốt hơn nhiều cho bất kỳ thứ gì bạn muốn làm.

24

Jersey 2.x:

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

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

Client client = ClientBuilder.newClient(clientConfig); 

tham khảo: 5.9.1. Http Authentication Support

+3

hoặc: Phản hồi phản hồi = client.target ("http: // localhost: 8080/rest/homer/contact") .request() .property (HTTP_AUTHENTICATION_BASIC_USERNAME, "homer") .property (HTTP_AUTHENTICATION_BASIC_PASSWORD, "p1swd745") .được(); – Dejell

0

Hãy tìm mã sau đây làm việc mà không SSL

Tôi đang sử dụng yêu cầu đặt, nếu cần bài/được chỉ cần thay đổi nó.

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 = "[email protected]"; 


      //{"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; 
    } 

} 
2

Thêm câu trả lời này như tôi tiếp tục tìm kiếm câu trả lời cho các phiên bản cũ của Jersey rằng không có liên quan còn 2.x.

Đối với Jersey 2 có một số cách. Hãy xem tại địa chỉ:

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

Đây là một trong đó là làm việc cho tôi (đơn giản nhất cơ bản 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)); 
0

Có cho áo 2.x bạn có thể thực hiện việc này để xác thực từng yêu cầu bằng auth cơ bản (chế độ ưu tiên):

client.register(HttpAuthenticationFeature.basic(userName, password)); 
// rest invocation code .. 
Các vấn đề liên quan