112.md 5.1 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# Jersey REST 客户端身份验证示例

> 原文: [https://howtodoinjava.com/jersey/jersey-rest-client-authentication/](https://howtodoinjava.com/jersey/jersey-rest-client-authentication/)

了解如何使用 [HttpAuthenticationFeature](https://github.com/jersey/jersey/blob/master/core-client/src/main/java/org/glassfish/jersey/client/authentication/HttpAuthenticationFeature.java) 构建**泽西休息客户端**,该客户端可用于访问身份验证/授权安全性后面的 REST API。 例如,我们将为在 [Jersey Secured REST API 教程](//howtodoinjava.com/jersey/jersey-rest-security/)中保护的服务创建 **jersey 客户端**; 并且我将扩展为 [**Jersey RESTful 客户端示例**](//howtodoinjava.com/jersey/jersey-restful-client-examples/) 创建的源代码。

```java
Table of Contents

1\. HttpAuthenticationFeature
2\. How to secure REST APIs
3\. Jersey REST Client Code
```

## 1\. Jersey 客户端– HttpAuthenticationFeature

`HttpAuthenticationFeature`类提供 HttpBasic 和 Digest 客户端身份验证功能。 该功能以 4 种模式之一工作,即 BASIC,BASIC NON-PREEMPTIVE,DIGEST 和 UNIVERSAL。 让我们快速了解它们。

1.  **基本** –一种抢占式身份验证方式,即信息始终与每个 HTTP 请求一起发送。 此模式必须与 SSL / TLS 结合使用,因为密码仅以 BASE64 编码发送。
2.  **基本非优先** –一种非优先的身份验证方式,即仅当服务器拒绝带有 401 状态码的请求后再添加身份验证信息,才添加身份验证信息。
3.  **DIGEST** – HTTP 摘要认证。 不需要使用 SSL / TLS。
4.  **UNIVERSAL** –非抢占模式下基本身份验证和摘要身份验证的组合,即在 401 响应的情况下,将根据 WWW-Authenticate HTTP 标头中定义的请求身份验证使用适当的身份验证。

要使用`HttpAuthenticationFeature`,请构建一个实例并向客户端注册。

W
wizardforcel 已提交
26
#### 1.1 基本认证方式
W
wizardforcel 已提交
27 28 29 30 31 32 33 34 35

```java
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password");

final Client client = ClientBuilder.newClient();
client.register(feature);

```

W
wizardforcel 已提交
36
#### 1.2 基本身份验证-非强制模式
W
wizardforcel 已提交
37 38 39 40 41 42 43 44 45 46 47 48

```java
 HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
     								.nonPreemptive()
     								.credentials("username", "password")
     								.build();

final Client client = ClientBuilder.newClient();
client.register(feature);

```

W
wizardforcel 已提交
49
#### 1.3 通用模式
W
wizardforcel 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63

```java
//HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal("username", "password");

//Universal builder having different credentials for different schemes
HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder()
				.credentialsForBasic("username1", "password1")
				.credentials("username2", "password2").build();

final Client client = ClientBuilder.newClient();
client.register(feature);

```

W
wizardforcel 已提交
64
## 2\. 如何保护 REST API
W
wizardforcel 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

对于启用身份验证的其余 api,请使用与角色相关的注释,例如`@RolesAllowed`。 例如,这是安全的 REST API 的代码。

```java
@Path("/employees")
public class JerseyService 
{
	@RolesAllowed("ADMIN")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public Employees getAllEmployees() 
	{
		Employees list = new Employees();
		list.setEmployeeList(new ArrayList<Employee>());

		list.getEmployeeList().add(new Employee(1, "Lokesh Gupta"));
		list.getEmployeeList().add(new Employee(2, "Alex Kolenchiskey"));
		list.getEmployeeList().add(new Employee(3, "David Kameron"));

		return list;
	}
}

```

W
wizardforcel 已提交
91
> 阅读更多:[Jersey 安全 REST API 教程](//howtodoinjava.com/jersey/jersey-rest-security/)
W
wizardforcel 已提交
92 93 94

## 3\. Jersey REST 客户端代码

W
wizardforcel 已提交
95
以下是**Jersey 休息客户端基本身份验证**示例,该示例接受用于身份验证的用户名和密码详细信息。
W
wizardforcel 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

```java
public static void main(String[] args) throws IOException 
{
	httpGETCollectionExample();
}

private static void httpGETCollectionExample() 
{
	ClientConfig clientConfig = new ClientConfig();

	HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("howtodoinjava", "password");
	clientConfig.register( feature) ;

	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient( clientConfig );
	WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");

	Invocation.Builder invocationBuilder =	webTarget.request(MediaType.APPLICATION_JSON);
	Response response = invocationBuilder.get();

	System.out.println(response.getStatus());
	System.out.println(response.getStatusInfo());

	if(response.getStatus() == 200)
	{
		Employees employees = response.readEntity(Employees.class);
		List<Employee> listOfEmployees = employees.getEmployeeList();
		System.out.println(Arrays.toString( listOfEmployees.toArray(new Employee[listOfEmployees.size()]) ));
	}
}

```

W
wizardforcel 已提交
131
#### 3.1 使用正确的用户名/密码输出
W
wizardforcel 已提交
132 133 134 135 136 137 138 139

```java
200
OK
[Employee [id=1, name=Lokesh Gupta], Employee [id=2, name=Alex Kolenchiskey], Employee [id=3, name=David Kameron]]

```

W
wizardforcel 已提交
140
#### 3.2 使用不正确的用户名/密码输出
W
wizardforcel 已提交
141 142 143 144 145 146 147 148 149 150

```java
401
Unauthorized

```

将您的查询放在评论部分。

学习愉快!