Search code examples
spring-mvcjunitspring-securityintegration-testing

Spring Integration testing doesn't use security configuration


I am new to integration testing and doing everything everything as in tutorials. My security config:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/ticket/create")
                .access("hasAnyAuthority('MANAGER','EMPLOYEE')")
                .and().authorizeRequests().antMatchers("/api/**","/ticket/*")
                .access("isAuthenticated()")
                .and().formLogin().loginPage("/login").failureUrl("/login?error")
                .and().formLogin().defaultSuccessUrl("/ticket/all", true)
                .usernameParameter("email")
                .passwordParameter("password")
                .and().csrf().disable();
    }

All of my app requires login.

Now i'm trying to run a simple test to view main page of my app which: /ticket/all

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppInit.class, WebMvcConfig.class, WebSecurityConfig.class, HibernateConfig.class, SecurityWebApplicationInitializer.class})
@WebAppConfiguration
public class TicketLoginControllerTest extends TestCase {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setup() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testTicketOverviewAll() throws Exception {
        mockMvc.perform(get("/ticket/all"))
                .andExpect(status().isOk());

    }
}

Test pass, even though i'm not authenticated.

Now my url: /ticket/create is forbidden for role ENGINEER

but when i try

@Test
public void testTicketOverviewAll() throws Exception {
    mockMvc.perform(get("/ticket/create"))
            .andExpect(status().isOk());

}

it still ok, when it should be 401 forbidden even if logged in.

I'm probably doing something wrong with test configuration but i don't know what exactly. Any help apreciated. If i just run my server and try all of the above, it will work as i expect it to work.


Solution

  • first i need to say mockMvc to use security config in @Before with line .apply(springSecurity())

    @Before
        public void setup() {
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
                    .apply(springSecurity())
                    .build();
        }
    

    And then all your request will require authentication which you can pass by adding .with(user("username").password("pass").roles("list of your roles") to a get/post or any other method.