如何使用只有 tokenValue 的 OAuth2RestTemplate?

How to use OAuth2RestTemplate having only tokenValue?

当其他应用程序使用访问令牌作为参数调用起始端点时,应用程序启动。访问令牌是一种字符串。

然后我必须调用其他几个端点,其中身份验证基于该令牌。

是否可以创建 OAuth2RestTemplate 来发出只有 tokenValue 而没有访问令牌 uri 的请求?

据我所知,你可以通过实现AccessTokenProvider接口并设置它来实现:

https://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/client/token/AccessTokenProvider.html

虽然,OAuth2RestTemplate就是为了给你简化这种流程的使用。如果您的使用是直截了当的,那么使用默认的 RestTemplate 并使用 HTTP 规范可能会更好。因此,为此,您应该使用 Bearer 类型的 Authorization header。像这样:

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + tokenValue);

并在您的请求中使用此 header,如下所示:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<BodyClass> response = restTemplate.exchange(url, HttpMethod.GET, request, BodyClass.class);
BodyClass body = response.getBody();

希望对您有所帮助。