Bahij.Mik
Bahij.Mik

Reputation: 1484

Spring Security causing problems when doing unit tests on REST controller

So basically i am doing some unit tests on my rest controller, before using spring security everything was working smoothly, after adding it and setting the spring security to my mockmvc, it's always returning a 302 and nothing else, after tinkering with my code and the browser i found out that after logging in, i am indeed receiving a 302 code which is as intended because of the redirection, it seems that the loginProcessingUrl in my configuration is causing this:

My spring security configuration:

 @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/showMyLoginPage")
                .loginProcessingUrl("/authenticateTheUser")
                .permitAll()
                .and()
                .logout()
                .logoutSuccessUrl("/")
                .logoutUrl("/logoutUser")
                .and()
                .csrf()
                .disable();
    }

The REST method i am testing:

    @GetMapping(path = "/list/getProducts")
    public String getProducts()
    {
        List<Product> products = productService.getProducts();
        return gson.toJson(products);
    }

And finally my test:

@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "file:src/test/java/resources/ProductCRUD-servlet.xml")
@WebAppConfiguration
public class ProductControllerTest
{

    @Autowired
    WebApplicationContext context;

    @InjectMocks
    private ProductRestController productRestController;

    @Mock
    private ProductService productService;

    private MockMvc mockMvc;

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

    @Test
    public void getAllProductsTest() throws Exception
    {
        List<Product> products = new ArrayList<>();
        products.add(new Product("4532", 123, "Product test", "test"));
        Mockito.when(productService.getProducts())
                .thenReturn(products);
        mockMvc.perform(MockMvcRequestBuilders
                .get("/product/list/getProducts"))
                .andExpect(status().isOk)
                .andExpect(content().string(containsString("\"productId\":\"4534\"")));    
    }

So what is happening is, even though my website is working and i am retrieving my json, the login process is messing up my test somehow.

enter image description here

Even if i set my test status code to 302 instead of 200, it isn't returning anything.

Expected :a string containing "\"productId\":\"4534\""
Actual   :""

TLDR: When testing my REST api which is protected by spring security, i am not able to reach the api from the tests.

Upvotes: 1

Views: 775

Answers (1)

xerx593
xerx593

Reputation: 13261

For spring security integration tests, we can use @WithMockUser as the methods proposed by 11. Testing Method Security (current spring-security guide).

However it is also good to test "resticted scenarios", where we would provide unauthorized/omit/anonymous user, and assert for the according reactions (exceptions, http codes, redirects,...).

Upvotes: 1

Related Questions