toni07 toni07 - 1 year ago 161
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:[email protected] scheme). I get a 401 error with this code:

final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<String> wsCalendarResponse = restTemplate.getForEntity("https://user:[email protected]", String.class);

If i copy.paste the exact same URL in a browser (
https://user:[email protected]
), it works fine.

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


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:[email protected]";
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 ="username");
   final String password ="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 =, HttpMethod.GET, request, String.class);

This is working fine, even if there are no credentials.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download