当前位置: 首页 > 知识库问答 >
问题:

在Spring Boot中禁用@webmvctest的Spring Security配置类

红智鑫
2023-03-14

最近,我使用以下类将Spring Security添加到Spring Boot项目中:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig {
}

因此,默认情况下,我的所有URL现在都受到身份验证和自生成密码的保护。

问题是我用于单元测试控制器的@WebMVCTest类中的所有测试:

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {...}

由于缺乏授权,现在到处都失败了。

问题:我能告诉@test方法忽略授权,这样它们就能像以前一样继续成功吗?

如何防止在特定的@WebMVCTEST单元测试类上选择@EnableWebSecurity配置类?

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {

    @Configuration
    @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class})
    static class ContextConfiguration { }

 ....}

共有1个答案

阎宾实
2023-03-14

您可以在@webmvctest注释中设置secure=false。它将跳过测试中的spring security MockMvc自动配置

@WebMvcTest(controllers = SomeController.class, secure = false)
public class SomeControllerTest {

作者注:截至2021年,这个答案已经过时了几年,很可能对你不起作用了。

 类似资料:
  • 我使用了一个简单的Spring Boot应用程序,它在Eureka中注册自己,并使用Spring cloud配置来读取一些属性。 是这样的: 我有一个rest控制器,我想为它编写一个测试。测试将使用mockmvc。简化示例如下: 控制器: 测试:

  • 有没有办法绕过授权?

  • 我知道在DispatcherServlet之外使用请求范围bean需要一些配置,并且已经阅读了http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-oth,但是还没有成功: 对于Servlet3.0+,这可以通过WebApplicationIni

  • 似乎Springboot自动配置自己来使用Tomcat的Logback。我想禁用它,并使用我在类路径中提供的一个。 LoggerFactory不是LoggerContext,但Logback位于类路径上。删除Logback或类[org.slf4j.impl.SimpleLoggerFactory]的竞争实现(类org.slf4j.impl.SimpleLoggerFactory)对象必须是类ch.

  • null 非常感谢你的帮助

  • 我在学习Spring Boot时遇到了一些编码问题;我想添加一个像Spring3.x那样的CharacterEncodingFilter。就像这样: