在 RestTemplate 中使用 Token

Use Token in RestTemplate

我想使用此 RestTemplate 代码发出 POST 个请求。

@Bean(name = "simpleRestTemplate")
    public RestTemplate getRestClient() {

        RestTemplate restClient = new RestTemplate(getClientHttpRequestFactory());
        restClient.getInterceptors().add(new BasicAuthorizationInterceptor("username", "password"));
        HttpEntity<PaymentTransaction> request = new HttpEntity<>(new PaymentTransaction());
        ResponseEntity<PaymentTransaction> response = restClient.exchange("http://example.com", HttpMethod.POST,
                request, PaymentTransaction.class);
        PaymentTransaction foo = response.getBody();

        return restClient;
    }

如何将 Toke 身份验证添加到 HTTP link?

可能最简单的方法是使用 exchange("http://example.com" + "/" + token, HttpMethod.POST,

有没有更好的办法?

查看 UriComponentsBuilder

URI uri = UriComponentsBuilder.fromUriString("http://example.com")
    .pathSegment(token)
    .build()
    .toUri();

然后您可以使用 exchange(),它以 URI 作为第一个参数。

restClient.exchange(uri, HttpMethod.POST, request, PaymentTransaction.class);

正如@nickb 评论的那样,身份验证最好在 HTTP headers 中完成。

如果确实需要在URL中注入token,可以实现自定义拦截器。

伪代码:

final String tokenValue = "something";

restClient.getInterceptors().add(new ClientHttpRequestInterceptor() {

    @Override
    ClientHttpResponse intercept(HttpRequest request,
                         byte[] body,
                         ClientHttpRequestExecution execution)
                         throws java.io.IOException {

        URI modifiedUri = UriComponentsBuilder.fromUri(request.getURI())
        .query("token={tokenPlaceholder}")
        .buildAndExpand(tokenValue)
        .toUri();

        request.setURI(modifiedUri);
    }
});

不这样做的原因有很多,例如:

  1. 拦截和记录的系统 URL 也会记录令牌,允许第 3 方冒充您的用户
  2. 您需要解析 URL 中的令牌,同时处理 POST body 请求中的其余查询

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/client/ClientHttpRequestInterceptor.html