API клиента Джерси - аутентификация
Я использую API-интерфейс клиента Jersey для отправки SOAP-запросов на веб-сервис JAX-WS. По умолчанию Джерси каким-то образом использует мои учетные данные Windows Nt для аутентификации при опросе. Может ли кто-нибудь объяснить, где Джерси это делает в коде? И может ли это быть преодолено?
Я попытался использовать HTTPBasicAuthFilter и добавив в качестве фильтра на клиенте. Я также попытался добавить мои учетные данные в поле запроса WebResoruce queryParams, но ни то, ни другое не подхвачено.
Ответы
Ответ 1
Сначала я получил эту работу, как описано в руководстве пользователя Jersey.
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)
Ответ 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-аутентификации
Ответ 3
В руководстве пользователя Джерси есть небольшой раздел о Client authentication. Я рекомендую вам следовать его советам и попытаться использовать Apache HTTP Client вместо HttpURLConnection, так как он имеет гораздо лучшую поддержку практически всего, что вы хочу сделать.
Ответ 4
Добавление этого ответа, когда я продолжаю находить ответы на более старые версии Джерси, которые больше не актуальны в 2.x.
Для Джерси 2 есть несколько способов.
Взгляните на:
JavaDoc для org.glassfish.jersey.client.authentication.HttpAuthenticationFeature
Вот тот, который работает для меня (простейший базовый 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) );
Ответ 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, если вам нужно сообщение/получить его просто изменить.
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;
}
}
Ответ 7
Да для джерси 2.x вы можете сделать это, чтобы аутентифицировать каждый запрос с базовым режимом auth (preemptive mode):
client.register(HttpAuthenticationFeature.basic(userName, password));
// rest invocation code ..