Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot 2, Spring Security 5 and @WithMockUser

Since I migrated to Spring Boot 2.0.5 from 1.x, with no mean to disable security, I can't get test roles to work on mock MVC tests :

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationsControllerShould {
    ...
    @Autowired
    private MockMvc mockMvc;
    private ObjectMapper mapper = new ObjectMapper();

    @Test
    @WithMockUser(roles = "ADMIN")
    public void handle_CRUD_for_applications() throws Exception {
        Application app = Application.builder()
                .code(APP_CODE).name(APP_NAME)
                .build();
        mockMvc.perform(post("/applications")
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(mapper.writeValueAsString(app)))
                .andExpect(authenticated())
                .andExpect(status().isOk());    // failure 403!
...

My controller endpoint isn't even protected!

@RestController
@RequestMapping("/applications")
public class ApplicationsController {
    ...
    @PostMapping
    public Application addApplication(@RequestBody Application application) {
        Assert.isTrue(!applicationsDao.existsById(application.getCode()), "Application code already exists: " + application.getCode());
        return applicationsDao.save(application);
    }
}

So I have in the test a session (#authenticated fails when @WithMockUser is commented out) and a role by the way (ROLE_ADMIN is visible in traces) but my request is being rejected and I don't understand what I did wrong. Thx for any idea!

like image 472
Thomas Escolan Avatar asked Oct 02 '18 07:10

Thomas Escolan


People also ask

What is and () in Spring Security?

Basically and() method is used to concatenate multiple configurer of Spring Security You can refer attached image to understand more clearly.

Why is WebSecurityConfigurerAdapter deprecated?

0-M2 we deprecated the WebSecurityConfigurerAdapter , as we encourage users to move towards a component-based security configuration. To assist with the transition to this new style of configuration, we have compiled a list of common use-cases and the suggested alternatives going forward.

What is UsernamePasswordAuthenticationToken Spring Security?

The UsernamePasswordAuthenticationToken is an implementation of interface Authentication which extends the interface Principal . Principal is defined in the JSE java. security . UsernamePasswordAuthenticationToken is a concept in Spring Security which implements the Principal interface.

What is Spring Security HasRole?

HasRole checks the granted authorities for the currently authenticated principal. So really when you see hasRole("blah") really means hasAuthority("blah"). In the case I've seen, you do this with a class that Implements UserDetails which defines a method called getAuthorities.


1 Answers

Ok... the good old CSRF stuff, then...

logging.level.org.springframework.security=DEBUG

2018-10-02 10:11:41.285 DEBUG 12992 --- [ main] o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost/applications/foo

    Application app = Application.builder()
            .code(APP_CODE).name(APP_NAME)
            .build();
    mockMvc.perform(post("/applications").with(csrf())    // oups...
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(mapper.writeValueAsString(app)))
            .andExpect(authenticated())
            .andExpect(status().isOk());    // there we go!
like image 80
Thomas Escolan Avatar answered Sep 20 '22 12:09

Thomas Escolan