简体   繁体   中英

How to skip authentication for TestRestTemplate in Spring Boot Tests?

Below is my test class. The hello-world endpoint simply returns an HTML page containing text ie Hello Stranger!

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloWorldTest {

    @Autowired
    private HelloWorldController controller;

    @Autowired
    private TestRestTemplate restTemplate;

    @LocalServerPort
    private int port;

    @Test
    public void contextLoads() throws Exception {
        assertThat(controller).isNotNull();
    }

    @Test
    public void greetingShouldReturnDefaultMessage() throws Exception {

        String baseUrl = "http://localhost:" + port;

        assertThat(this.restTemplate.getForObject(baseUrl+"/hello-world", String.class))
                .contains("Hello Stranger!");
    }
}

This is my Security Config:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }
}

It simply redirects all authenticated users to the login page

I have tried adding @WithMockUser annotation or adding another security config class in my test directory to override the default config. But so far nothing has seemed to work.

Any help or suggestions on documentation to read is appreciated!

I have managed to solve this issue by first creating another web security config without requiring login/authorization, then by adding @Profile to my config class and production/dev/test profile via application.properties in my test directory (ie adding "spring.profiles.active=test" ).

Not sure if this is the best way to solve this issue, but it works for now.

Another way to do it that worked for me was to override the normal security configation for running the integration test like so:

@TestConfiguration
@Order(-101)
@EnableWebSecurity
class TestSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security.httpBasic().and().formLogin().disable();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM