简体   繁体   English

Spring RestTemplate URL中的基本身份验证

[英]Spring RestTemplate Basic authentication in URL

I know there are existing discussions on this topic, but I was not able to find an answer to my situation: I want to pass credentials directly through the URL (following the https://user:pass@url scheme). 我知道有关于这个主题的现有讨论,但我无法找到我的情况的答案:我想直接通过URL传递凭证(遵循https:// user:pass @ url scheme)。 I get a 401 error with this code: 我用这段代码得到401错误:

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

If i copy.paste the exact same URL in a browser ( https://user:pass@foobarbaz.com ), it works fine. 如果我在浏览器中复制.paste完全相同的URL( https://user:pass@foobarbaz.com ),它可以正常工作。

Any clue, more simple than this answer: Basic authentication for REST API using spring restTemplate ? 任何线索,比这个答案更简单: 使用spring restTemplate进行REST API的基本身份验证

Thanks 谢谢

Well, it seems Spring RestTemplate does not hold Basic authentication in URL. 好吧,看起来Spring RestTemplate在URL中不支持基本身份验证。 So I added some code before the URL call, to make it take into account if there are credentials in the 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);

This is working fine, even if there are no credentials. 即使没有凭据,这也可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM