Spring 4.0.0 basic authentication with RestTemplate

前端 未结 6 1714
梦谈多话
梦谈多话 2020-12-13 10:37

I am currently working on integration of a third party application with our local reporting system. I would like to implement REST calls with basic authentication but facing

6条回答
  •  时光说笑
    2020-12-13 11:05

    Since Spring 4.3.1 there is a simplier way using BasicAuthorizationInterceptor, which is also independent of underlying http client used in RestTemplate.

    The example that uses RestTemplateBuilder from spring-boot to add BasicAuthorizationInterceptor to RestTemplate:

    @Configuration
    public class AppConfig {
    
        @Bean
        public RestTemplate myRestTemplate(RestTemplateBuilder builder) {
            return builder
                    .rootUri("http://my.cool.domain/api/")
                    .basicAuthorization("login", "password")
                    .build();
        }
    
    }
    

    This way any request sent using myRestTemplate bean instance will include given basic authorization header. So be careful to not use the same RestTemplate bean instance to send requests to foreign domains. The rootUri is partially protects from this, but you can always pass the absolute URL when making the request using RestTemplate instance, so be careful!

    If you are not using spring-boot, you can also manually add this interceptor to your RestTemplate following this answer.

提交回复
热议问题