How to add basic auth to Autowired testRestTemplate in SpringBootTest; Spring Boot 1.4

My OAuth integration test before Spring Boot 1.4 looked as follows(updates just to not use deprecated features):

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ApplicationConfiguration.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
public class OAuth2IntegrationTest {

    @Value("${local.server.port}")
    private int port;

    private static final String CLIENT_NAME = "client";
    private static final String CLIENT_PASSWORD = "123456";

    @Test
    public void testOAuthAccessTokenIsReturned() {
        MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
        request.set("username", "user");
        request.set("password", password);
        request.set("grant_type", "password");
        @SuppressWarnings("unchecked")
        Map<String, Object> token = new TestRestTemplate(CLIENT_NAME, CLIENT_PASSWORD)
            .postForObject("http://localhost:" + port + "/oauth/token", request, Map.class);
        assertNotNull("Wrong response: " + token, token.get("access_token"));
    }
}

I now want to use Autowired TestRestTemplate as stated here http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-working-with-random-ports

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
    ApplicationConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class OAuth2IntegrationTest {

    private static final String CLIENT_NAME = "client";
    private static final String CLIENT_PASSWORD = "123456";

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Test
    public void testOAuthAccessTokenIsReturned() {
        MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
        request.set("username", "user");
        request.set("password", password);
        request.set("grant_type", "password");
        @SuppressWarnings("unchecked")

        Map<String, Object> token1 = this.testRestTemplate. //how to add basic auth here
        assertNotNull("Wrong response: " + token, token.get("access_token"));
    }
}

I saw this as the closest way to add auth:

Spring 4.0.0 basic authentication with RestTemplate

I want to use the Autowired testRestTemplate to avoid resolving host and ports in my test. Is there a way to do this?

This got fixed in Spring Boot 1.4.1 which has an additional method

testRestTemplate.withBasicAuth(USERNAME,PASSWORD)

@Autowired
private TestRestTemplate testRestTemplate;

@Test
public void testOAuthAccessTokenIsReturned() {
    MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
    request.set("username", USERNAME);
    request.set("password", password);
    request.set("grant_type", "password");
    @SuppressWarnings("unchecked")
    Map<String, Object> token = this.testRestTemplate.withBasicAuth(CLIENT_NAME, CLIENT_PASSWORD)
            .postForObject(SyntheticsConstants.OAUTH_ENDPOINT, request, Map.class);
    assertNotNull("Wrong response: " + token, token.get("access_token"));
}

How to add basic auth to Autowired testRestTemplate in , Spring Boot Test and Spring Security: Perform Http Basic Authentication with TestRestTemplate. What is HTTP Basic Authentication? If you want  There are different ways that can be used to perform Basic Authentication with TestRestTemplate. Authentication headers ‘withBasicAuth’ method With Authenticated TestRestTemplate object. Lets look at each of those approaches in detailed as follows. 1. Authentication headers. In this approach, authentication string is added and sent in the HTTP request header (Authorization header and Basic Scheme). e.g:- Authorization Basic xxxxxxx

There is a better solution so you don't need to retype withBasicAuth part each time

@Autowired
private TestRestTemplate testRestTemplate;

@BeforeClass
public void setup() {
    BasicAuthorizationInterceptor bai = new BasicAuthorizationInterceptor(CLIENT_NAME, CLIENT_PASSWORD);
    testRestTemplate.getRestTemplate().getInterceptors().add(bai);
}

@Test
public void testOAuthAccessTokenIsReturned() {
    MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
    request.set("username", USERNAME);
    request.set("password", password);
    request.set("grant_type", "password");
    @SuppressWarnings("unchecked")
    Map<String, Object> token = this.testRestTemplate.postForObject(SyntheticsConstants.OAUTH_ENDPOINT, request, Map.class);
    assertNotNull("Wrong response: " + token, token.get("access_token"));
}

Spring Boot Test and Spring Security: Perform Http Basic , Spring Test & Spring Boot Test — Utilities and integration test support for Don't forget to also add @RunWith(SpringRunner.class) to your test, RANDOM_PORT) public class MyWebIntegrationTests { @Autowired private TestRestTemplate You can get a vanilla template or one that sends Basic HTTP authentication  Setting up the RestTemplate. Bootstrapping the RestTemplate into the Spring context can be done by simply declaring a bean for it; however, setting up the RestTemplate with Basic Authentication will require manual intervention, so instead of declaring the bean directly, a Spring FactoryBean will be used for more flexibility.

Although the accepted answer is correct, in my case I had to replicate the testRestTemplate.withBasicAuth(...) in each test method and class.

So, I tried to define in src/test/java/my.microservice.package a configuration like this:

@Configuration
@Profile("test")
public class MyMicroserviceConfigurationForTest {

    @Bean
    public TestRestTemplate testRestTemplate(TestRestTemplate testRestTemplate, SecurityProperties securityProperties) {
        return testRestTemplate.withBasicAuth(securityProperties.getUser().getName(), securityProperties.getUser().getPassword());
    }

}

That seems to have the effect of overriding the default TestRestTemplate definition, allowing the injection of a credentials-aware TestRestTemplate anywhere in my test classes.

I'm not entirely sure whether this is really a valid solution but you can give it a try...

40. Testing, They are fault tolerant, and optionally can carry Basic authentication headers. If you are using the @SpringBootTest annotation with an embedded server, a TestRestTemplate is automatically available and can be @Autowired into your test. If you need customizations (for example to adding additional message converters)  For example, to add BASIC auth support you can use builder.basicAuthorization("user", "password").build(). Table of Contents Example of RestTemplate supply Basic Authentication:

I think there is a better solution if you are still using Basic Authentication in your application, with the "user.name" and "user.password" properties set on your application.properties file:

public class YourEndpointClassTest {
    private static final Logger logger = LoggerFactory.getLogger(YourEndpointClassTest.class);  

    private static final String BASE_URL = "/your/base/url";

    @TestConfiguration
    static class TestRestTemplateAuthenticationConfiguration {

        @Value("${spring.security.user.name}")
        private String userName;

        @Value("${spring.security.user.password}")
        private String password;

        @Bean
        public RestTemplateBuilder restTemplateBuilder() {
            return new RestTemplateBuilder().basicAuthentication(userName, password);
        }
    }


    @Autowired
    private TestRestTemplate restTemplate;

//here add your tests...

TestRestTemplate (Spring Boot 2.3.1.RELEASE API), To create a client for a REST API – a RestTemplate instance is typically used. Before Spring Boot 1.4.0, the procedure of testing a Spring REST client error handlers, URI template handlers, basic authorization and also use any This allows us to autowire the DetailsServiceClient instance inside our  TestRestTemplate provides a constructor with which we can create a template with specified credentials for basic authentication. All requests performed using this instance will be authenticated using provided credentials: TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd"); ResponseEntity<String> response = testRestTemplate.

Quick Guide to @RestClientTest in Spring Boot, @runwith(springrunner.class) @springboottest(classes //how add basic auth here assertnotnull("wrong response: " + token, token.get("access_token")); } this got fixed in spring boot 1.4.1 has additional method. Learn to consume HTTP POST REST API with Spring TestRestTemplate. In this post request test example, we will be sending request body along with request headers. Execute the test class as JUnit test. It will start the server and deploy the API as it will be done normally. Then It will execute the

How to add basic auth to Autowired testRestTemplate in , RELEASE; H2 In-memory Database 1.4.197; Tomcat Embed 9.0.14; JUnit 4.12 Include spring-boot-starter-security for Spring Security and In below example, we will use the HTTP Basic authentication to protect the REST endpoints. //@​WithMockUser is not working with TestRestTemplate @Autowired  @RunWith (SpringRunner. class) @SpringBootTest (webEnvironment = WebEnvironment. RANDOM_PORT) public class HelloControllerIT {@Autowired private TestRestTemplate testRestTemplate; @Test public void testHelloEndpoint {HttpHeaders headers = new HttpHeaders (); // place your headers here final ResponseEntity < String > response = testRestTemplate

Spring REST + Spring Security Example, But I figure it could be a nice feature of Spring Boot Test to handle predefined class MyTest { @Autowired private TestRestTemplate template; @Test public void You don't need to mimic its logic just to add basic auth. hey guys, im upgrading another project from Spring Boot 1.3.6 to 1.4.0 but its the first  Learn to create and import test configuration in spring boot applications with the help of @TestConfiguration annotation.. 1. @TestConfiguration annotations @TestConfiguration is specialized form of @Configuration that can be used to define additional beans or customizations for a test.

Comments
  • public TestRestTemplate withBasicAuth(String username, String password) this looks to be only available in spring boot 1.4.1, is this the solution
  • Is there a way to do that in a more central place? This way I would have to repeat the password in every testcase that needs Basic Auth. Can the TestRestTemplate be used to always use basic auth somehow? How can I inject the testRestTemplate as a @Bean?
  • This does not work as setup method needs to be static
  • You can try with @BeforeEach, no need to be static