我有一个Spring Web服务器,它使用Keycloak作为身份验证代理。 我想从另一台也使用spring的服务器发出请求。为了实现这一目标,我应首先从Keycloak请求令牌,然后使用此令牌发出其他请求。
我能够使用RestTemplate发出请求并获取有效令牌:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> mapForm = new LinkedMultiValueMap<>();
mapForm.add("grant_type", "password");
mapForm.add("client_id", "admin-cli");
mapForm.add("username", "admin");
mapForm.add("password", "admin");
ResponseEntity<Object> response = restTemplate.exchange(AUTH_SERVER_URI, HttpMethod.POST, request, Object.class);
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>)response.getBody();
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(mapForm, headers);
if (map != null) {
this.accessToken = (String)map.get("access_token");
this.tokenType = (String)map.get("token_type");
this.refreshToken = (String)map.get("refresh_token");
this.expires_in = (int)map.get("expires_in");
this.scope = (String)map.get("scope");
} else {
System.out.println("Not a good user+password combination");
}
我在这里获得了访问令牌,但不幸的是,在我发出请求后,我得到了403 Forbidden Exception。这就是我使用令牌发出请求的方式:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);
RestTemplate restTemplate = new RestTemplate();
String resourceUrl = "http://localhost:8080/api/queries/";
HttpEntity<QueryDTO> requestUpdate = new HttpEntity<>(queryDTO, headers);
restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, QueryDTO.class);
为什么我做错了?
稍后编辑:
代码没问题,但我不得不在服务器端停用CSRF,因为我是从非浏览器发出请求的。