【问题标题】:Spring RestTemplate Basic authentication in URLURL中的Spring RestTemplate基本身份验证
【发布时间】:2017-12-22 04:50:18
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

  • 答案有帮助吗?因为 RestTemplate 和身份验证仍然存在一些问题,Apache 客户端无法立即解决。

标签: java spring authentication resttemplate


【解决方案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);

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

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 2018-01-22
    • 2012-02-21
    • 2014-03-22
    • 2016-08-24
    • 2015-09-25
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多