【问题标题】:Spring Security Unit Test - MockMvc perform test with custom userSpring Security Unit Test - MockMvc 使用自定义用户执行测试
【发布时间】:2016-08-02 09:43:56
【问题描述】:

我正在为我的 Spring MVC 控制器设置单元测试,并且我正在尝试利用 Spring MVC 测试框架。对于我的控制器中的每个端点,我想确保只有具有指定权限的用户才能访问。我的问题是我使用自定义 User 实现并在使用 mockMvc 工具时获取类转换异常。

对于每个请求,我希望它看起来像这样:

 mockMvc.perform(MockMvcRequestBuilders.get(path).with(user("user").authorities(authorities)))
                .andExpect(status().isOk())
                .andExpect(authenticated().withUsername("user"));

我想以某种方式调整上述语句以指定我的自定义用户主体。请参阅下面的 Spring 的用户方法。我的第一个想法是我会覆盖 UserRequestPostProcessor 类并对其进行调整,以便它使用我的自定义用户类型而不是标准 Spring Security 用户,但是这个类被声明为 final 并且不能被子类化。是否支持覆盖默认行为并使用自定义用户类型?

public static UserRequestPostProcessor user(String username) {
        return new UserRequestPostProcessor(username);
}

据我所知,我是使用@WithSecurityContext 注释我的测试的候选人,以便我可以在身份验证中设置我的自定义用户主体。我在这里担心的是,我将仅限于为每种方法测试一个用户,而这并不适合我正在尝试做的事情。

如何测试多个自定义用户的请求?

【问题讨论】:

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


    【解决方案1】:

    我学到了两种方法:

    1. 我可以创建一个类来实现 UserDetails 并扩展我的 自定义用户主体类。然后我可以将其作为参数传递 到用户方法。

    2. 我可以完全从头开始使用用户方法,并传入我的 已使用我的自定义用户主体设置身份验证。

    我选择了后者。

    protected void performTest(HttpMethod method, String path, Object[] pathVariables, UserRoleEnum role,
            boolean expectAllowed) throws Exception {
        mockMvc.perform(buildRequest(method, path, pathVariables).with(authentication(createAuthentication(role))))
                .andExpect(expectAllowed ? status().isNotFound() : status().isForbidden())
                .andExpect(authenticated().withUsername("user"));
    }
    

    注意 - buildRequestcreateAuthentication 方法是我创建的辅助方法,而所有其他方法均由 Spring 提供。辅助方法分别返回MockHttpServletRequestBuilderAuthentication

    【讨论】:

    • createAuthentication方法的内容是什么?
    • createAuthentication 方法是什么?好奇的人想知道!
    猜你喜欢
    • 2018-04-27
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    相关资源
    最近更新 更多