dermoritz
dermoritz

Reputation: 13011

WebMVC tests failing after adding spring security, how to fix all at once?

I just added spring-boot-starter-security and spring-security-test to my Spring Boot application. I want to protect controllers and methods.

Now all my controller tests (@WebMvcTest) are all failing. It seems that all GET methods fail with 401 and all POST/DELETE/PUT fail with 403.

I can easily fix the 401 by using @WithMockUser.

What is the easiest way to get all tests running again? I don't want to consider security in these tests. Later i want to add specific tests for security.

Upvotes: 1

Views: 1273

Answers (1)

jzheaux
jzheaux

Reputation: 7772

Spring Security automatically adds CSRF defense to every POST, DELETE, and PUT request, so that is why you are seeing the 403.

You can disable CSRF protection, though this is an important defense mechanism, so disabling isn't generally recommended. Spring Security has some information in their reference docs for how to determine when CSRF protection is necessary.

Instead, you can have Spring Security add in a test CSRF token to your tests by configuring your Mock Mvc instance:

this.mockMvc.perform(post("/").with(csrf()))

Where csrf() is from SecurityMockMvcRequestPostProcessors.

Note that the reason your tests are failing will be the same reason that POSTs, etc. will fail in your application - they will also be expecting a CSRF token as part of the request.

Upvotes: 2

Related Questions