【问题标题】:SpringBoot: WebMvcTest with authorizationSpringBoot:具有授权的 WebMvcTest
【发布时间】:2017-10-12 16:46:54
【问题描述】:

我有一个基本的 SpringBoot 应用程序。使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR 文件。

我有这个测试:

@RunWith(SpringRunner.class)
@WebAppConfiguration
@WebMvcTest
public class MockMvcTests {

    // Pull in the application context created by @ContextConfiguration
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @MockBean
    private I18NService i18NService;

    @MockBean
    private EmailService emailService;

    @MockBean
    private PasswordResetTokenService passwordResetTokenService;

    @MockBean
    private UserService userService;

    @MockBean
    private CompanyService companyService;

    @MockBean
    private UserSecurityService userSecurityService;

    @Before
    public void setup() {
        // Setup MockMVC to use our Spring Configuration
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    /**
     * 
     * @throws Exception
     *             If anything fails.
     */
    @Test
    public void getDeviceEventsTest() throws Exception {
        this.mockMvc
                .perform(get("/deviceevent/list") //
                .accept(MediaType.parseMediaType("text/html;charset=UTF-8")))
                .andExpect(status().isOk()) //
                .andExpect(model().size(1)); //
    }

但是运行测试我得到了这个异常

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#authorization.expression('hasRole(''ROLE_ADMIN'')')" (tdk/common/menu:62)

有没有办法绕过授权?

【问题讨论】:

  • 添加认证头怎么样? .perform(get("/deviceevent/list").header("Authorization", "your auth type header value"))

标签: spring spring-mvc spring-boot spring-security thymeleaf


【解决方案1】:

我在奇怪的表达中看到了第一个可能的问题 hasRole(''ROLE_ADMIN''),在这里看起来像两个单引号而不是双引号,但可能只是在日志中看起来很奇怪。

无论如何,要绕过测试的身份验证机制,您需要在测试模式下禁用 Spring Security,有一些工作方式描述了here

我通常使用this 方式进行配置和配置文件设置,因为它比其他描述的方式更灵活。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-02
    • 2017-05-31
    • 2019-04-30
    • 2019-04-28
    • 1970-01-01
    • 2020-12-28
    • 2020-05-12
    • 2018-05-15
    相关资源
    最近更新 更多