mockMvc 不理解具有多个匹配器的 securityConfig

mockMvc doesn't understand securityConfig with multiple Matchers

我的安全配置:

http.authorizeRequests().antMatchers("/ticket/create")
                .access("hasAnyAuthority('MANAGER','EMPLOYEE')")
                .and().authorizeRequests().antMatchers("/api/**","/ticket/*")
                .access("isAuthenticated()")
                .and().formLogin().loginPage("/login").failureUrl("/login?error")
                .and().formLogin().defaultSuccessUrl("/ticket/all", true)
                .usernameParameter("email")
                .passwordParameter("password")
                .and().csrf().disable();

如您所见,我有 /ticket/* 需要任何身份验证,但在我具有更高优先级之前 /ticket/create 只有 2 个角色可用。

在实时服务器上它工作正常,但是当我尝试编写测试时,returns 403 被禁止,就好像我没有访问权限一样。 我的测试:

@Test
    public void testTicketCreate() throws Exception {

        logger.info("Test: Create Ticket Page");
        mockMvc.perform(get("/ticket/create").with(user("user").password("123").roles("MANAGER")))
                .andExpect(status().isOk())
                .andExpect(view().name("createTicket"));

    }

如果我将测试从 /ticket/create 更改为任何其他 url,例如 /ticket/{id},它将通过同一用户。

当您指定用户具有 .roles("MANAGER") 时,这会赋予该用户同等的权限 "ROLE_MANAGER".
您的安全配置正在寻找权限 "MANAGER",而不是 "ROLE_MANAGER"
您可以将测试用户更改为使用 .authorities(new SimpleGrantedAuthority("MANAGER")),而不是 .roles("MANAGER")