【问题标题】:Spring Integration testing doesn't use security configurationSpring Integration 测试不使用安全配置
【发布时间】:2019-09-30 11:17:22
【问题描述】:

我是集成测试的新手,并且在教程中做所有事情。 我的安全配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        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/all

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppInit.class, WebMvcConfig.class, WebSecurityConfig.class, HibernateConfig.class, SecurityWebApplicationInitializer.class})
@WebAppConfiguration
public class TicketLoginControllerTest extends TestCase {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setup() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testTicketOverviewAll() throws Exception {
        mockMvc.perform(get("/ticket/all"))
                .andExpect(status().isOk());

    }
}

测试通过,即使我没有通过身份验证。

现在我的 url: /ticket/create 被禁止用于角色 ENGINEER

但是当我尝试时

@Test
public void testTicketOverviewAll() throws Exception {
    mockMvc.perform(get("/ticket/create"))
            .andExpect(status().isOk());

}

还是可以的,登录的时候应该是401禁止。

我可能在测试配置方面做错了,但我不知道到底是什么。任何帮助表示赞赏。 如果我只是运行我的服务器并尝试上述所有方法,它将按我预期的那样工作。

【问题讨论】:

    标签: spring-mvc junit spring-security integration-testing


    【解决方案1】:

    首先我需要说 mockMvc 在@Before 中使用安全配置 .apply(springSecurity())

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

    然后您的所有请求都需要身份验证,您可以通过添加 .with(user("username").password("pass").roles("list of your roles") 到 get/post 或任何其他方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 2015-08-16
      • 2015-08-10
      • 2020-10-02
      • 1970-01-01
      相关资源
      最近更新 更多