1

Let's say we have the following piece of the web security configuration:

http
    .and().formLogin()
      .loginProcessingUrl("/api/authentication")
      .successHandler(authenticationSuccessHandler)
      .failureHandler(authenticationFailureHandler)
      .usernameParameter("j_username")
      .passwordParameter("j_password")
      .permitAll()

How should I pass the authentication process using the TestRestTemplate in my integration tests?

1 Answers1

3

TestRestTemplate provides a method called withBasicAuth() so you can use like

testRestTemplate.withBasicAuth(
  "user", "passwd").getForEntity(YOUR_URL, String.class)

If you are using an older version, you can try something like this

HttpHeaders headers = new HttpHeaders();
String auth = "userid" + ":" + "password";
byte[] encodedAuth = Base64.encode(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String( encodedAuth );
headers.set("Authorization", authHeader );

that way you are generating the authentication headers yourself

Luiz E.
  • 6,769
  • 10
  • 58
  • 98
  • Unfortunately, I'm using an old version of Spring Boot where this method isn't available. Creating a TestRestTemplate instance and specifying the username and password doesn't change anything. I still get the 401 HTTP code in the response when I'm trying to access some REST endpoint. –  May 31 '18 at 09:51
  • and the constructor? I think you can pass the username and password to `TestRestTemplate` in order to use basic auth like `new TestRestTemplate("user", "passwd")` – Luiz E. May 31 '18 at 09:53
  • Yes, I was talking about using the constructor which accepts the username and password. Nothing happens. I still get the 401 error code. –  May 31 '18 at 09:56
  • 1
    I upgraded the version to 1.4.1 and used this method 'withBasicAuth' you mentioned earlier. Unfortunately, I still get the 401 HTTP code. –  May 31 '18 at 10:09
  • how is your `authenticationManager` configured? – Luiz E. May 31 '18 at 10:15
  • I'm using the default implementation which uses my UserDetailsService implementation. I should probably mention that the loadUserByUsername doesn't get invoked when I run my integration tests. –  May 31 '18 at 10:33
  • then probably there is something going wrong before the app invoke the authentication – Luiz E. May 31 '18 at 10:37