将授权标头添加到泽西岛 SSE 客户端请求

我正在使用泽西岛客户端连接到 SSE 流。服务器要求我在http请求中添加一个标头以进行授权,但我无法弄清楚如何添加标头。

这是我的代码:

Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
WebTarget target = client.target(baseurl + "/v1/devices/events/");
eventSource = EventSource.target(target).build();
eventSource.register(getEventListener());
eventSource.open();

以下是我需要添加的标头的示例:

Authorization: Bearer 38bb7b318cc6898c80317decb34525844bc9db55

答案 1

对于基本身份验证,它将是这样的:

Client client = ClientBuilder.newClient();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().build();
client.register(feature);
client.register(SseFeature.class);
WebTarget target = client.target(baseurl + "/v1/devices/events/")
    .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_USERNAME, "...")
    .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_PASSWORD, "...");

...

您已经获得了泽西岛编码的密码。

如果它是一个令牌:

Client client = ClientBuilder.newClient();
WebTarget target = client.target(baseurl + "/v1/devices/events/")
    .request("...")     
    .header(HttpHeaders.AUTHORIZATION, "Bearer " + "... encoded token ...");

希望它有帮助!


答案 2

如果有人想在实体级别本身而不是实体级别添加持有者令牌标头(在我的情况下,我有一个用于返回预配置实体的工厂方法,因此我无法在工厂方法中添加授权标头,因为只有在您通过调用链后才可用, 截至泽西岛2.x):ClientRequestClient.header(...)ClientBuilder.newBuilder().register(...).build().target(...).request(...)

// client is a javax.ws.rs.client.Client entity
Feature feature = OAuth2ClientSupport.feature("YOUR_BEARER_TOKEN");
client.register(feature);
// now you can use client.target(...).request(...).post(...), without calling .header(...) after .request(...)

不幸的是(正如您可能已经猜到的那样),这需要一个新的依赖项:org.glassfish.jersey.security:oauth2-client

<dependency>
  <groupId>org.glassfish.jersey.security</groupId>
  <artifactId>oauth2-client</artifactId>
  <version>2.15</version>
</dependency>

推荐