Ekaterina
Ekaterina

Reputation: 1892

Authorization and TestRestTemplate

I'm using a default Spring login form and REST API for other data. Sessions are enabled and used.

All urls (except /login form ) are protected.

So how to test the protected @RestController methods using TestRestTemplate? (I could make an additional request to /api/login to get Cookie and then generate and add Headers, but there is no REST endpoint for login, only a form-base authencation).

Also, is the @WithMockUser annotation only for MockMvc (and can't be used with TestRestTemplate)?

Upvotes: 2

Views: 1769

Answers (1)

Steps

  1. Clone spring security example repo git clone https://github.com/spring-guides/gs-securing-web.git
  2. Added RestControllerIT
  3. Added csrf().disable() to WebSecurityConfig. This test will not pass if csrf enabled
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RestControllerIT {

    @Autowired
    TestRestTemplate testRestTemplate;

    @LocalServerPort
    int localPort;

    @Test
    public void test(){
        String securedUrl = "http://localhost:" + localPort + "/hello";
        String loginUrl = "http://localhost:" + localPort + "/login";
        String username = "user";
        String password = "password";

        MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
        form.set("username", username);
        form.set("password", password);
        ResponseEntity<String> loginResponse = testRestTemplate.postForEntity(
                loginUrl,
                new HttpEntity<>(form, new HttpHeaders()),
                String.class);
        String cookie = loginResponse.getHeaders().get("Set-Cookie").get(0);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cookie", cookie);
        ResponseEntity<String> responseFromSecuredEndPoint = testRestTemplate.exchange(securedUrl, HttpMethod.GET, new HttpEntity<>(headers), String.class);

        assertEquals(responseFromSecuredEndPoint.getStatusCode(), HttpStatus.OK);
        assertTrue(responseFromSecuredEndPoint.getBody().contains("Hello World!"));
    }
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
             User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(user);
    }
}

Upvotes: 1

Related Questions