WIthMockUser不起作用

时间:2016-03-24 12:16:26

标签: spring spring-security spring-test-mvc

我无法使用@WithMockUser,无论我做什么,它都不会在春季测试中提供授权用户。也许这是因为它的资源服务器但是......

配置:

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

测试课

@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"));
...
}

我一直在获得401 Access is denied (user is anonymous); redirecting to authentication entry point。我试过在注释参数中设置用户名,角色,将with(user..)传递给mockMvc,没有任何帮助。这是春季安全4.0.4.RELEASE。

1 个答案:

答案 0 :(得分:1)

好吧,它可以在设置无状态'之后起作用。参数为' false'如下所述:https://github.com/spring-projects/spring-security-oauth/issues/385

并使用with(user..

ResultActions response = mockMvc.perform(post("/bucket/key")
            .with(user("john@example.com"))
            .content("value"));

WithMockUser仍无法正常工作,但此方法现在还不错。

相关问题