복붙노트

[SPRING] spring restTemplate을 사용한 REST API의 기본 인증

SPRING

spring restTemplate을 사용한 REST API의 기본 인증

RestTemplate과 REST API에서도 완전히 새로운 기능을 제공합니다. Jira REST API를 통해 애플리케이션에서 일부 데이터를 가져오고 싶지만 401 Unauthorized로 돌아가고 싶습니다. Jira 나머지 API 문서에 대한 기사를 찾았으나이 예제를 사용하여 커맨드 라인을 사용하여 java로 다시 작성하는 방법을 실제로 알지 못합니다. 다시 제안하는 방법에 대한 제안이나 조언을 부탁드립니다.

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/rest/api/2/issue/QA-31"

스프링 휴식 템플릿을 사용하여 자바에. ZnJlZDpmcmVk는 base64로 인코딩 된 username : password 문자열입니다. 고맙습니다.

해결법

  1. ==============================

    1.이 사이트의 예제를 보면 헤더 값을 채우고 헤더를 템플릿에 전달하여 가장 자연스러운 방법이라고 생각합니다.

    이 사이트의 예제를 보면 헤더 값을 채우고 헤더를 템플릿에 전달하여 가장 자연스러운 방법이라고 생각합니다.

    이것은 헤더 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);
    

    그리고 이것은 헤더를 REST 템플릿에 전달하는 것입니다.

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

    2.Spring-boot RestTemplateBuilder를 사용할 수 있습니다.

    Spring-boot RestTemplateBuilder를 사용할 수 있습니다.

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

    설명서보기

    (SB 2.1.0 이전에는 #basicAuthorization이었습니다)

  3. ==============================

    3.Spring Boot의 TestRestTemplate 구현을 다음과 같이 참조하십시오 :

    Spring Boot의 TestRestTemplate 구현을 다음과 같이 참조하십시오 :

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

    특히 다음과 같이 addAuthentication () 메서드를 참조하십시오.

    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));
    }
    

    마찬가지로 RestTemplate을 쉽게 만들 수 있습니다.

    다음과 같이 TestRestTemplate과 같은 상속에 의해 :

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

  4. ==============================

    4.(아마) 스프링 부트를 가져 오지 않고 가장 쉬운 방법입니다.

    (아마) 스프링 부트를 가져 오지 않고 가장 쉬운 방법입니다.

    restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));
    
  5. ==============================

    5.다음과 같이 인스턴스화하는 대신 :

    다음과 같이 인스턴스화하는 대신 :

    TestRestTemplate restTemplate = new TestRestTemplate();
    

    그냥 이렇게해라.

    TestRestTemplate restTemplate = new TestRestTemplate(user, password);
    

    그것은 나를 위해 작동합니다, 나는 그것이 도움이되기를 바랍니다!

  6. ==============================

    6.Spring 5.1부터 HttpHeaders.setBasicAuth를 사용할 수있다.

    Spring 5.1부터 HttpHeaders.setBasicAuth를 사용할 수있다.

    기본 권한 부여 헤더 생성 :

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

    RestTemplate에 헤더를 전달하십시오.

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

    선적 서류 비치: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBasicAuth-java.lang.String-java.lang.String-

  7. from https://stackoverflow.com/questions/21920268/basic-authentication-for-rest-api-using-spring-resttemplate by cc-by-sa and MIT license