Spring RestTemplate URL中的基本身份验证

时间:2017-07-17 15:13:07

标签: java spring authentication resttemplate

我知道有关于这个主题的现有讨论,但我无法找到我的情况的答案:我想直接通过URL传递凭证(遵循https://user:pass@url计划)。我用这段代码得到401错误:

final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<String> wsCalendarResponse = restTemplate.getForEntity("https://user:pass@foobarbaz.com", String.class);

如果我在浏览器中复制.paste完全相同的网址(https://user:pass@foobarbaz.com),它可以正常工作。

任何线索,比这个答案更简单:Basic authentication for REST API using spring restTemplate

由于

1 个答案:

答案 0 :(得分:1)

好吧,看起来Spring RestTemplate在URL中不支持基本身份验证。所以我在URL调用之前添加了一些代码,以便在URL中有凭据时将其考虑在内:

final String urlWs = "https://user:pass@foobarbaz.com";
final HttpHeaders headers = new HttpHeaders();
final String pattern = "^(?<protocol>.+?//)(?<username>.+?):(?<password>.+?)@(?<address>.+)$";
final Pattern regExpPattern = Pattern.compile(pattern);
final Matcher matcher = regExpPattern.matcher(urlWs);
if(matcher.find()) {
   final String username = matcher.group("username");
   final String password = matcher.group("password");
   final String plainCreds = username + ":" + password;
   final byte[] plainCredsBytes = plainCreds.getBytes();
   final byte[] base64CredsBytes = Base64Utils.encode(plainCredsBytes);
   final String base64Creds = new String(base64CredsBytes);
   headers.add("Authorization", "Basic " + base64Creds);
}
final HttpEntity<String> request = new HttpEntity<String>(headers);
final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<String> wsCalendarResponse = restTemplate.exchange(urlWs, HttpMethod.GET, request, String.class);

即使没有凭据,这也可以正常工作。