Search code examples
springspring-securityspring-test-mvc

WIthMockUser doesn't work


I can't use @WithMockUser, no matter what I do it doesn't provide authorized user in spring test. Maybe it's because its resource server but..

Config:

@Configuration
@EnableResourceServer
class ResourceServerConfig extends ResourceServerConfigurerAdapter 
...
    @Override
    public void configure(HttpSecurity http) throws Exception {
    http
            .anonymous().and().authorizeRequests().antMatchers("/**").hasRole("USER");
}
...
}

And test class

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


@Test
@WithMockUser()
public void shouldAddValueToStore() throws Exception {
ResultActions response = mockMvc.perform(post("/bucket/key")
            .content("value"));
...
}

I keep getting 401 Access is denied (user is anonymous); redirecting to authentication entry point. I've tried with setting usernames, roles in annotation parameters, passing with(user..) to mockMvc, nothing helps. It's spring security 4.0.4.RELEASE.


Solution

  • ok, it works after setting 'stateless' parameter to 'false' as described here: https://github.com/spring-projects/spring-security-oauth/issues/385

    and using with(user..

    ResultActions response = mockMvc.perform(post("/bucket/key")
                .with(user("[email protected]"))
                .content("value"));
    

    WithMockUser is still not working, but this method is good enough for now.