Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 332
Tuhin Kanti Sharma Avatar asked Sep 23 '16 01:09

Tuhin Kanti Sharma


People also ask

How do you add basic authentication to RestTemplate?

Now that everything is in place, the RestTemplate will be able to support the Basic Authentication scheme just by adding a BasicAuthorizationInterceptor: restTemplate. getInterceptors(). add( new BasicAuthorizationInterceptor("username", "password"));

How do you set authorization bearer token in RestTemplate?

Setting bearer token for a GET request RestTemplate restTemplate = new RestTemplate(); String customerAPIUrl = "http://localhost:9080/api/customer"; HttpHeaders headers = new HttpHeaders(); headers. set("Authorization", "Bearer " + accessToken); //accessToken can be the secret key you generate.


2 Answers

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"));
}
like image 139
Tuhin Kanti Sharma Avatar answered Oct 21 '22 22:10

Tuhin Kanti Sharma


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"));
}
like image 39
celezar Avatar answered Oct 22 '22 00:10

celezar