Basic authentication for REST API using spring restTemplate

前端 未结 8 1211
眼角桃花
眼角桃花 2020-11-29 21:02

I am completely new in RestTemplate and basically in the REST APIs also. I want to retrieve some data in my application via Jira REST API, but getting back 401 Unauthorised.

相关标签:
8条回答
  • 2020-11-29 21:36

    Reference Spring Boot's TestRestTemplate implementation as follows:

    https://github.com/spring-projects/spring-boot/blob/v1.2.2.RELEASE/spring-boot/src/main/java/org/springframework/boot/test/TestRestTemplate.java

    Especially, see the addAuthentication() method as follows:

    private void addAuthentication(String username, String password) {
        if (username == null) {
            return;
        }
        List<ClientHttpRequestInterceptor> interceptors = Collections
                .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                        username, password));
        setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
                interceptors));
    }
    

    Similarly, you can make your own RestTemplate easily

    by inheritance like TestRestTemplate as follows:

    https://github.com/izeye/samples-spring-boot-branches/blob/rest-and-actuator-with-security/src/main/java/samples/springboot/util/BasicAuthRestTemplate.java

    0 讨论(0)
  • 2020-11-29 21:38

    Taken from the example on this site, I think this would be the most natural way of doing it, by filling in the header value and passing the header to the template.

    This is to fill in the header Authorization:

    String plainCreds = "willie:p@ssword";
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);
    
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);
    

    And this is to pass the header to the REST template:

    HttpEntity<String> request = new HttpEntity<String>(headers);
    ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
    Account account = response.getBody();
    
    0 讨论(0)
提交回复
热议问题