2011-07-21 19 views
40

JerseyクライアントAPIを使用してJAX-WS WebサービスにSOAPリクエストを送信しています。デフォルトでは、Jerseyは挑戦を受けたときに認証のためにWindows Ntの資格情報を使用しています。誰もがジャージーがコードでこれを行う場所を説明できますか?それは上書きすることができますか?Jersey Client API - 認証

私はHTTPBasicAuthFilterを使用して、クライアントでフィルタとして追加しようとしました。 WebResoruceのqueryParamsフィールドに自分の資格情報を追加しようとしましたが、どちらも選択されていません。

答えて

65

は、最初に私はこの作業を得ました。いくつかの研究の後、私はジャージーが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)

+0

これは私が探していたものです。私はこれをクライアントに追加し、サーバー上でSpring Securityを使用しました。非常にエレガントに作業して、アプリケーションにセキュリティを追加しました。 – bh5k

+0

Jersey 2.xの回答を参照してください – Dejell

+0

私はこれをしました: 'HTTPBasicAuthFilter feature = new HTTPBasicAuthFilter(restUsername、restPassword); client.addFilter(feature); 'いくつかの未知の理由のために、私は' null'として機能を取得し続けます。なぜそれは起こるだろう、どんな考え? – HitchHiker

12

ジャージーユーザーガイドの小部分はClient authenticationです。私は、アドバイスに従って、HttpURLConnectionの代わりにApache HTTP Clientを使ってみることをお勧めします。それはグローバルオーセンティケータの設定に依存していたとして、私はこれが好きではなかったしかしジャージーユーザーガイド

Authenticator.setDefault (authinstance); 

に記載されているように

24

ジャージー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

+3

か:応答レスポンス= client.target( "にhttp:// localhost:8080 /休憩/ホームラン/接触").request() .property(HTTP_AUTHENTICATION_BASIC_USERNAME、 "ホームラン") .property(HTTP_AUTHENTICATION_BASIC_PASSWORD、 "p1swd745") 。取得する(); – Dejell

0

必要ポスト/はそれを変更する得れば、私はPUT要求を使用していますSSL

せずに、作業コード、次の見つけてください。

の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 = "[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

私は、もはや関連しているジャージーの古いバージョンのための答えを見つける保つようこの回答を追加します2.x.

ジャージー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)); 
0

はい、ジャージー2です。x基本認証(プリエンプティブモード)で各リクエストを認証するためにこれを行うことができます:

client.register(HttpAuthenticationFeature.basic(userName, password)); 
// rest invocation code .. 
関連する問題