Spring boot,禁用测试安全性

2024-04-19

我使用 Spring Boot 版本“1.3.0.M5”(我也尝试过版本“1.2.5.RELEASE”)。我添加了弹簧安全:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

和代码:

@SpringBootApplication
public class SpringBootMainApplication {
  public static void main(String[] args) {
    SpringApplication.run(SpringBootMainApplication.class, args);
  }
}

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
  }
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers("/api/sampleentity").authenticated()
    .and().authorizeRequests()
    .and().formLogin().permitAll()
    .and().logout().permitAll().logoutUrl("/logout")
    .logoutSuccessUrl("/");
  }
  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
}

@RestController
@RequestMapping("/api/sampleentity")
public class SampleEntityController {
  @RequestMapping(method= RequestMethod.GET)
  public Iterable<SampleEntity> getAll() {
    return ImmutableSet.of();
  }
  @RequestMapping(method=RequestMethod.POST)
  @ResponseStatus(value= HttpStatus.CREATED)
  public SampleEntity create(@RequestBody SampleEntity sampleEntity) {
    return sampleEntity;
  }
}

访问 /api/sampleentity 时失败的测试: org.springframework.web.client.HttpClientErrorException: 403 Forbidden (...)

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootMainApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0"})
public class SampleEntityTest {
  @Value("${local.server.port}")
  private int port;
  private String url;
  private RestTemplate restTemplate;
  @Autowired
  private ApplicationContext context;
  @BeforeClass
  public static void authenticate(){
//ONE TRY
//        Authentication authentication =
//                new UsernamePasswordAuthenticationToken("user", "password",
//                                                        AuthorityUtils.createAuthorityList("USER")); //tried "ROLE_USER"
//        SecurityContextHolder.getContext().setAuthentication(authentication);
  }
  @Before
  public void setUp() {
    url = String.format("http://localhost:%s/api/sampleentity", port);
    restTemplate = new RestTemplate();
//ANOTHER TRY
//        AuthenticationManager authenticationManager = context.getBean(AuthenticationManager.class);
//        Authentication authentication = authenticationManager
//                .authenticate(new UsernamePasswordAuthenticationToken("user", "password", AuthorityUtils.createAuthorityList("USER"))); //tried "ROLE_USER"
//        SecurityContextHolder.getContext().setAuthentication(authentication);
  }
  //THIS METHOD SHOULD WORK !
  @Test
//ANOTHER TRY
//@WithMockUser(username="user",password = "password", roles={"USER"})//tried "ROLE_USER"
  public void testEntity_create() throws Exception {
    SampleEntity sampleEntity = create("name", 1);
    ResponseEntity<SampleEntity> response = restTemplate.postForEntity(url, sampleEntity, SampleEntity.class);
    assertEquals(HttpStatus.CREATED, response.getStatusCode());
  }
  private SampleEntity create(String name, int id) {
    SampleEntity entity = new SampleEntity();
    entity.setName(name);
    entity.setId(id);
    return entity;
  }
}

当我从 main() 运行应用程序并访问 url 时:http://localhost:8080/api/sampleentity http://localhost:8080/api/sampleentity我被重定向到登录页面。

如何运行测试并禁用安全性或仅登录用户?

--我的解决方案:使用配置文件从测试中排除安全性:

@SpringBootApplication
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class})
public class SpringBootMainApplication {body the same}

@EnableWebSecurity
@Import(SecurityAutoConfiguration.class)
@Profile("!test")
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {body the same}

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootMainApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0"})
@ActiveProfiles("test")
public class SampleEntityTest {body the same}

您必须对配置进行一些更改并进行测试才能解决您的问题。

首先,我将解释为什么您的解决方案不起作用:

  1. 春天RestTemplate类是访问 REST 服务的一种可能方法,但它的构造方式缺少一些标头信息(这并不意味着不可能使用RestTemplate)。这就是身份验证不起作用的原因。
  2. 我的第一个解决方案尝试不起作用,因为使用了RestTemplate类,作为RestTemplate请求可能会创建一个新会话。它设置了一个完全不同的环境。如果您想测试使用以下方法保护的方法,我的代码可以工作@PreAuthorize注释,但仅当您想在测试中直接执行此类方法并且需要有效的身份验证时。
  3. 从当前的 spring security 配置来看,您无法自动授权任何用户。

其次,以下是对代码的必要更改:

首先是配置类

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.inMemoryAuthentication().withUser("user").password("password").roles("USER" );
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().csrf().disable()
    .authorizeRequests().antMatchers("/api/sampleentity").authenticated()
    .and().authorizeRequests().antMatchers("/users").hasRole("ADMIN")
    .and().formLogin().permitAll()
    .and().logout().permitAll().logoutUrl("/logout")
    .logoutSuccessUrl("/");
  }

  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
}

我必须添加 httpBasic 身份验证支持(以通过 http 标头属性启用身份验证),并且禁用了 csrf 令牌(后者只是为了方便,您应该根据应用程序的重要性重新启用它们)。

第二个测试类:

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

import javax.servlet.Filter;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootMainApplication.class)
@WebAppConfiguration
@IntegrationTest({ "server.port=0" })
public class SampleEntityTest {

private String url;
private MockMvc mockMvc;
private HttpMessageConverter mappingJackson2HttpMessageConverter;

private MediaType contentType = new MediaType(
        MediaType.APPLICATION_JSON.getType(),
        MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Autowired
private WebApplicationContext webApplicationContext;

@Autowired
private Filter springSecurityFilterChain;

@Autowired
void setConverters(HttpMessageConverter<?>[] converters) {
    for (HttpMessageConverter hmc : Arrays.asList(converters)) {
        if (hmc instanceof MappingJackson2HttpMessageConverter) {
            this.mappingJackson2HttpMessageConverter = hmc;
        }
    }

    Assert.assertNotNull("the JSON message converter must not be null",
            this.mappingJackson2HttpMessageConverter);
}

@Before
public void setUp() {
    url = "/api/sampleentity";
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
            .addFilters(springSecurityFilterChain).build();
}

@Test
public void testEntityGet() throws Exception {
    mockMvc.perform(
            get(url)
            .with(httpBasic("user", "password")))
            .andExpect(status().isOk());
}

@Test
public void testEntityPost() throws Exception {
    SampleEntity sampleEntity = new SampleEntity();
    sampleEntity.setName("name");
    sampleEntity.setId(1);
    String json = json(sampleEntity);
    mockMvc.perform(
            post(url)
            .contentType(contentType)
            .content(json)
            .with(httpBasic("user", "password")))
            .andExpect(status().isCreated());
}

protected String json(Object o) throws IOException {
    MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage();
    this.mappingJackson2HttpMessageConverter.write(o,
            MediaType.APPLICATION_JSON, mockHttpOutputMessage);
    return mockHttpOutputMessage.getBodyAsString();
}

}

我在这里使用了 spring/spring 安全测试方法。

使用的版本:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.5.RELEASE</version>
    </parent>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>4.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <version>4.0.2.RELEASE</version>
        <scope>test</scope>
    </dependency>

如果你想测试你的rest api,我可以推荐你 Chrome 的 Postman 插件。因为这可以帮助您更快地识别问题。

我希望这可以帮助您最终解决您的问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring boot,禁用测试安全性 的相关文章

  • SWT - 表查看器 - 隐藏列并从列中获取值

    我正在尝试从表中的数据创建一个数组列表 我需要从可见列中获取值 但我还需要从表中不可见的列中获取值 将 SWT 与表查看器一起使用 我不知道如何不显示表中的列 我也不知道如何通过指定列名从表中提取数据 我一直使用 Swing 所以我一直使用
  • spring boot feign 客户端获取 HTTP 404

    我目前正在检查如何在我的项目之一中使用 Feign 作为声明式 REST 客户端 以下是假客户端 FeignClient name SEARCHCABMS configuration AppFeignConfiguration class
  • Javafx-场景快照不显示值和系列

    我制作了一个非常短的应用程序 它使用 javafx 生成图表 应用程序显示正确的值 图表 但当我做快照时 图像仅显示轴和标签 但不显示系列和值 stage setTitle Line Chart Sample final DateAxis
  • 如何在java中使用模式匹配器?

    假设字符串是我想提取xyz从字符串中出来 我用了 Pattern titlePattern Pattern compile lttitle gt s s lt title gt Matcher titleMatcher titlePatte
  • 增强的 jsp:include 实现

    一直困扰我的事情之一
  • 在基于 RESTful 的应用程序中管理状态

    我们正在评估用于基于 Web 的应用程序的技术 一些建议是采用基于 RESTful 的服务方法 技术堆栈 1 春天 2 Apache CXF JAX RS 我的问题是 1 如何在请求之间管理状态 例如 用户已经过身份验证 现在他正在发出一系
  • Java替换特殊字符

    我试图用仅包含特殊字符的模式替换文件中的特殊字符 但它似乎不起作用 String special Something great that special special replaceAll as 但是 当我运行时 我得到原始字符串而不是
  • 正则表达式删除2个字符串之间的所有内容

    我的replaceAll 需要一个正则表达式来删除2 个字符串和字符串本身之间的所有内容 例如 如果我有类似的东西 stackoverflow is really awesome nremove123 n I love it 我试图做一个像
  • ffmpeg 用于屏幕捕获?

    所以我有一个小程序来捕获屏幕和计算机麦克风的声音 然后屏幕截图被编码为 ScreenVideo2 声音被编码为 AAC 如何使用 ffmpeg 逐帧混合 然后将混合输出发送到 wowza 媒体服务器 如果用ffmpeg无法完成 您能提供一些
  • 使用简单的 UPDATE 查询“不支持 DML 操作”

    我收到错误Not supported for DML operations当我使用以下 HQL 时 Query UPDATE WorkstationEntity w SET w lastActivity timestamp WHERE w
  • 将resourceBundle与外部文件java一起使用

    我一直在阅读有关此问题的其他问题和答案 但我不明白资源边界是如何完全工作的 我认为这与 Joomla 使用多语言选项的方式类似 基本上 您有要阅读的不同语言的不同消息的文件 所以我在 src Lang 文件夹中创建了 System prop
  • EJB3 - 通过注入与查找获取 bean - 有什么区别、影响和陷阱?

    我知道有两种获取 EJB 实例的方法 通过 EJB 注释在 servlet 和 EJB 中进行依赖注入 在任何地方通过 Context lookup 进行 JNDI 查找 使用这两种方法有哪些差异 影响和陷阱 它们是一样的吗 依赖注入比查找
  • 必须指定 Spring Security 身份验证管理器 - 用于自定义过滤器

    我正在尝试创建自定义用户名密码身份验证过滤器 因为我需要验证来自两个不同来源的密码 我正在使用 Spring Boot 1 2 1 和 Java 配置 我在部署时遇到的错误是 Caused by org springframework be
  • Swing JTable:当行可见或滚动到底部时发生事件?

    我正在寻找一种方法 以便在 JTable 滚动时收到通知 以便特定行变得可见 或者在表底部滚动到视图中时失败 理想情况下 这应该在不轮询的情况下完成 而是通过一些事件触发来完成 有任何想法吗 Add a ChangeListener到滚动窗
  • jtree 编程式多选

    是否能够以编程方式选择 JTree 中的多个树节点 我已经设置了多选模式tree getSelectionModel setSelectionMode TreeSelectionModel DISCONTIGUOUS TREE SELECT
  • 改造 POST java.io.IOException:由 java.io.EOFException 引起的连接上的流意外结束:\n 未找到:

    我已经解决了与此相关的所有问题 但尚未找到适合我的解决方案 我在用着retrofit 2 8 1 and OkHttp 4 5 0 我的服务界面如下所示 public interface MlApiService POST Multipar
  • 在java中读取文本文件[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 当每行都包含整数 字符串和双精度数时 如何在 Java 中读取 txt 文件并将每一行放入数组中 每行都有不同数量的单词 数字 Try
  • java.lang.NullPointerException(无错误消息)APK构建

    Top level build file where you can add configuration options common to all sub projects modules buildscript repositories
  • 无法查找 Websphere 8.5 中是否启用了 SSL

    我编写了一个简单的 ejb 瘦客户端来查找 IBM WebSphere 8 5 中部署的 bean 当服务器上未启用 SSL 时 我能够成功查找 bean 但是一旦启用 SSL 我就开始收到下面提到的异常 This is how I ena
  • Spring Web 连接到嵌入 Jboss 服务器 7.1.1 的 HornetQ JMS

    我正在尝试设置 spring web 以通过以下方式连接到远程 Jboss 7 1 1 HornetQ JMSthis http java dzone com articles connecting spring地点 但我收到以下错误 是否

随机推荐

  • HTML
    标签导致 Rails 表单提交 GET 而不是 POST 请求

    我有一个可以正常工作的表单 直到我添加样式标签 我正在使用 twitter bootstrap 该应用程序是 Rails 3 1 我使用的是 Mac 这是一个可以正常工作的表格 没有任何问题 div class alert message
  • Android 数据库 - 无法执行此操作,因为连接池已关闭

    我对 android 数据库和游标有奇怪的问题 有时 很少 发生 我收到客户的崩溃报告 很难找出它崩溃的原因 因为我有大约 150 000 个活跃用户 可能每周大约有 1 个报告 所以这确实是一些小错误 这是例外 STACK TRACE j
  • 找不到 db4o 数据库文件

    您好 我正在编写一个简单的 CRUDE 应用程序 该应用程序使用 JSF 和 DB4O 完美运行 我可以正常添加并列出所有实体 不会出现错误 我使用此代码来保存实体 bd Db4oEmbedded openFile configuratio
  • 如何在传递一些上下文时在expressjs中重定向?

    我正在使用express 在node js 中制作一个网络应用程序 这是我所拥有的内容的简化 var express require express var jade require jade var http require http v
  • iOS照片框架

    我想检索所有照片local设备上的相册 基本上设备上的所有照片 本地标识符列表是否唯一 使用照片框架的最佳方法是什么 我的问题不重复 因为另一个问题还讨论了云资产和设备上没有的资产 当检索图像的实际数据时 它会在尝试获取同步时返回空数据 我
  • ModuleWithProviders 需要 1 个类型参数 - angular-autofocus-fix

    安装后angular autofocus fix 导入自动对焦模块 当我运行角度项目时 它显示以下错误 ERROR in node modules angular autofocus fix index d ts 4 23 error TS
  • 从数据表中获取隐藏行内容并将其与表单一起提交

    我遇到了一个问题 现在它占用了我的时间 我有一个包含 7 条记录的表 例如 该表具有 input 和 textarea 元素 用户可以在其中输入内容 现在 分页的值为每页 5 条记录 我有两个页面 用户在评论部分输入数据 单击分页中的 下一
  • viewWillAppear 与 Viewdidload ios

    当使用 iOS 导航应用程序编写代码时 我遇到了以下问题 我可以在哪里放置 UITableView 的 initdata 方法 在 viewWillAppear 或 viewDidLoad 中 请帮帮我 您可以根据应用程序的要求放置 ini
  • sql Sparklyr Sparkr Databricks 上的数据帧转换

    我在使用以下代码创建的数据块上有 sql 表 sql CREATE TABLE data USING CSV OPTIONS header true inferSchema true LOCATION url data csv 以下代码分别
  • Iptables v1.6.1 无法初始化 iptables 表“过滤器”Ubuntu 18.04 Bash Windows

    我正在从 Windows Bash 运行 Ubuntu 18 04 uname a Linux DESKTOP M87DGAS 4 4 0 17134 Microsoft 112 Microsoft Thu Jun 07 22 57 00
  • Mongo $in 与复合索引

    如何高效地做好 in使用复合索引查找集合 下面的示例中 索引位于字段 a 和 b 上 例如 db foo createIndex a 1 b 1 SQL 中的示例 SELECT FROM foo WHERE a b IN aVal1 bVa
  • 实体框架上下文 6.1.3 未刷新/销毁?

    在此单元测试中 我将验证内容字节列的 MD5 是否已正确计算 保存和获取 但是 实体框架 6 1 3 上下文似乎没有刷新 销毁 因为在原始 SQL UPDATE 明显生效之后 但在使用新上下文获取行时没有显示 namespace UnitT
  • 按时间合并 pandas 数据框和另一列

    我有两个熊猫数据框 我正在尝试将它们组合成一个数据框 我是这样设置它们的 a date 1 1 2015 00 00 1 1 2015 00 15 1 1 2015 00 30 num 1 2 3 b date 1 1 2015 01 15
  • dart 中“library”关键字的确切含义

    我知道这个关键字应该在一些自定义库中使用 但当我放下它时 什么也没有发生 至少我没有注意到任何事情 进口仍然运作良好 私人会员仍然是私人的 有人可以解释一下 Dart 中的 library 关键字的作用吗 更新2018 03 05 有一段时
  • 如何获取Recyclerview特定Item的ViewHolder

    有没有办法获得ViewHolder仅基于给定位置的回收者视图的特定项目 就像是getViewHolder position public MyViewHolder getViewHolder int position MyViewHolde
  • 无法在单元测试用例中调用@HostListener方法

    我使用创建了一个自定义指令 Directive我正在使用的 HostListener并且代码运行良好 现在 在编写测试用例时 我需要调用 HostListener单元测试用例中的方法 我还可以看到在代码覆盖率中代码没有被覆盖 以下是代码 焦
  • 如何通过 Internet Explorer 使用网络摄像头

    有什么办法可以跑getUserMedia在 Internet Explorer 中并使用网络摄像头 不使用 Flash 据此 没有 http caniuse com search getuserMedia http caniuse com
  • 将数据从模态内部的部分视图传递到主视图,然后关闭模态

    我有一个按钮 在我的中定义如下索引 cshtml file
  • 冷融合和分页

    首先 我对 ColdFusion 很陌生 但学得很快 因此 我正在尝试构建一个大型数据库 最初每页显示 25 行的所有结果 并有一个下一个 上一个链接来浏览页面 这一切都工作正常 但是当我执行搜索时 当新结果显示大约几页时 分页链接不起作用
  • Spring boot,禁用测试安全性

    我使用 Spring Boot 版本 1 3 0 M5 我也尝试过版本 1 2 5 RELEASE 我添加了弹簧安全