toni07 toni07 - 5 months ago 90
Java Question

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). I get a 401 error with this code:

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.

Any clue, more simple than this answer: Basic authentication for REST API using spring restTemplate ?

Thanks

Answer Source

Well, it seems Spring RestTemplate does not hold Basic authentication in URL. So I added some code before the URL call, to make it take into account if there are credentials in the 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.