Basic authentication for REST API using spring restTemplate

前端 未结 8 1210
眼角桃花
眼角桃花 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:11

    You may use spring-boot RestTemplateBuilder

    @Bean
    RestOperations rest(RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder.basicAuthentication("user", "password").build();
    }
    

    See documentation

    (before SB 2.1.0 it was #basicAuthorization)

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

    Use setBasicAuth to define credentials

    HttpHeaders headers = new HttpHeaders();
    headers.setBasicAuth("myUsername", myPassword);
    

    Then create the request like you prefer.

    Example:

    HttpEntity<String> request = new HttpEntity<String>(headers);
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, 
    request, String.class);
    String body = response.getBody();
    
    0 讨论(0)
  • 2020-11-29 21:17

    As of Spring 5.1 you can use HttpHeaders.setBasicAuth

    Create Basic Authorization header:

    String username = "willie";
    String password = ":p@ssword";
    HttpHeaders headers = new HttpHeaders();
    headers.setBasicAuth(username, password);
    ...other headers goes here...
    

    Pass the headers to the RestTemplate:

    HttpEntity<String> request = new HttpEntity<String>(headers);
    ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
    Account account = response.getBody();
    

    Documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBasicAuth-java.lang.String-java.lang.String-

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

    There are multiple ways to add the basic HTTP authentication to the RestTemplate.

    1. For a single request

    try {
        // request url
        String url = "https://jsonplaceholder.typicode.com/posts";
    
        // create auth credentials
        String authStr = "username:password";
        String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());
    
        // create headers
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Creds);
    
        // create request
        HttpEntity request = new HttpEntity(headers);
    
        // make a request
        ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);
    
        // get JSON response
        String json = response.getBody();
    
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    

    If you are using Spring 5.1 or higher, it is no longer required to manually set the authorization header. Use headers.setBasicAuth() method instead:

    // create headers
    HttpHeaders headers = new HttpHeaders();
    headers.setBasicAuth("username", "password");
    

    2. For a group of requests

    @Service
    public class RestService {
    
        private final RestTemplate restTemplate;
    
        public RestService(RestTemplateBuilder restTemplateBuilder) {
            this.restTemplate = restTemplateBuilder
                    .basicAuthentication("username", "password")
                    .build();
        }
    
       // use `restTemplate` instance here
    }
    

    3. For each and every request

    @Bean
    RestOperations restTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder.basicAuthentication("username", "password").build();
    }
    

    I hope it helps!

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

    (maybe) the easiest way without importing spring-boot.

    restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));
    
    0 讨论(0)
  • 2020-11-29 21:35

    Instead of instantiating as follows:

    TestRestTemplate restTemplate = new TestRestTemplate();
    

    Just do it like this:

    TestRestTemplate restTemplate = new TestRestTemplate(user, password);
    

    It works for me, I hope it helps!

    0 讨论(0)
提交回复
热议问题