Spring Security provides comprehensive integration with Spring MVC Test

Spring Security提供与Spring MVC Test的全面集成

12.1 Setting Up MockMvc and Spring Security

In order to use Spring Security with Spring MVC Test it is necessary to add the Spring Security FilterChainProxy as a Filter. It is also necessary to add Spring Security’s TestSecurityContextHolderPostProcessor to support Running as a User in Spring MVC Test with Annotations. This can be done using Spring Security’s SecurityMockMvcConfigurers.springSecurity(). For example:

为了将Spring Security与Spring MVC Test一起使用,有必要将Spring Security FilterChainProxy添加为Filter。还需要添加Spring Security的TestSecurityContextHolderPostProcessor以支持在带有Annotations的Spring MVC Test中作为用户运行。这可以使用Spring Security的SecurityMockMvcConfigurers.springSecurity()来完成。例如:
 

Spring Security’s testing support requires spring-test-4.1.3.RELEASE or greater.

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class CsrfShowcaseTests { @Autowired
private WebApplicationContext context; private MockMvc mvc; @Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity()) 1
.build();
} ...

1.SecurityMockMvcConfigurers.springSecurity() will perform all of the initial setup we need to integrate Spring Security with Spring MVC Test

SecurityMockMvcConfigurers.springSecurity()将执行我们将Spring Security与Spring MVC Test集成所需的所有初始设置

12.2 SecurityMockMvcRequestPostProcessors

Spring MVC Test provides a convenient interface called a RequestPostProcessor that can be used to modify a request. Spring Security provides a number of RequestPostProcessor implementations that make testing easier. In order to use Spring Security’s RequestPostProcessor implementations ensure the following static import is used:

Spring MVC Test提供了一个称为RequestPostProcessor的方便接口,可用于修改请求。 Spring Security提供了许多RequestPostProcessor实现,使测试更容易。为了使用Spring Security的RequestPostProcessor实现,请确保使用以下静态导入:
 
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

12.2.1 Testing with CSRF Protection

When testing any non-safe HTTP methods and using Spring Security’s CSRF protection, you must be sure to include a valid CSRF Token in the request. To specify a valid CSRF token as a request parameter using the following:

在测试任何非安全HTTP方法并使用Spring Security的CSRF保护时,您必须确保在请求中包含有效的CSRF令牌。要使用以下命令将有效的CSRF令牌指定为请求参数:
mvc.perform(post("/").with(csrf()))

If you like you can include CSRF token in the header instead:

如果您愿意,可以在标题中包含CSRF令牌:
mvc.perform(post("/").with(csrf().asHeader()))

You can also test providing an invalid CSRF token using the following:

mvc.perform(post("/").with(csrf().useInvalidToken()))

12.2.2 Running a Test as a User in Spring MVC Test

It is often desirable to run tests as a specific user. There are two simple ways of populating the user:

通常希望将测试作为特定用户运行。填充用户有两种简单的方法:

12.2.3 Running as a User in Spring MVC Test with RequestPostProcessor

There are a number of options available to associate a user to the current HttpServletRequest. For example, the following will run as a user (which does not need to exist) with the username "user", the password "password", and the role "ROLE_USER":

有许多选项可用于将用户与当前的HttpServletRequest相关联。例如,以下将以用户(不需要存在)的形式运行,用户名为“user”,密码为“password”,角色为“ROLE_USER”:
 

The support works by associating the user to the HttpServletRequest. To associate the request to the SecurityContextHolder you need to ensure that the SecurityContextPersistenceFilter is associated with the MockMvc instance. A few ways to do this are:

支持通过将用户与HttpServletRequest相关联来工作。要将请求与SecurityContextHolder相关联,您需要确保SecurityContextPersistenceFilter与MockMvc实例相关联。一些方法是:
  • Invoking apply(springSecurity())
  • Adding Spring Security’s FilterChainProxy to MockMvc
  • Manually adding SecurityContextPersistenceFilter to the MockMvc instance may make sense when using MockMvcBuilders.standaloneSetup
  • 使用MockMvcBuilders.standaloneSetup时,手动将SecurityContextPersistenceFilter添加到MockMvc实例可能有意义
mvc.perform(get("/").with(user("user")))

You can easily make customizations. For example, the following will run as a user (which does not need to exist) with the username "admin", the password "pass", and the roles "ROLE_USER" and "ROLE_ADMIN".

您可以轻松进行自定义。例如,以下将以用户名(admin,不需要存在)运行,用户名为“admin”,密码为“pass”,角色为“ROLE_USER”和“ROLE_ADMIN”。
mvc.perform(get("/admin").with(user("admin").password("pass").roles("USER","ADMIN")))

If you have a custom UserDetails that you would like to use, you can easily specify that as well. For example, the following will use the specified UserDetails (which does not need to exist) to run with a UsernamePasswordAuthenticationToken that has a principal of the specified UserDetails:

如果您有自己想要使用的自定义UserDetails,您也可以轻松指定它。例如,以下将使用指定的UserDetails(不需要存在)来运行具有指定UserDetails的主体的UsernamePasswordAuthenticationToken:
 
You can run as anonymous user using the following:
您可以使用以下方式以匿名用户身份运行:
mvc.perform(get("/").with(anonymous()))

This is especially useful if you are running with a default user and wish to execute a few requests as an anonymous user.

如果您使用默认用户运行并希望以匿名用户身份执行一些请求,则此功能尤其有用。
 
If you want a custom Authentication (which does not need to exist) you can do so using the following:
如果需要自定义身份验证(不需要存在),可以使用以下命令执行此操作:
mvc.perform(get("/").with(authentication(authentication)))

You can even customize the SecurityContext using the following:

您甚至可以使用以下方法自定义SecurityContext:
mvc.perform(get("/").with(securityContext(securityContext)))

We can also ensure to run as a specific user for every request by using MockMvcBuilders's default request. For example, the following will run as a user (which does not need to exist) with the username "admin", the password "password", and the role "ROLE_ADMIN":

我们还可以通过使用MockMvcBuilders的默认请求确保以每个请求的特定用户身份运行。例如,以下将以用户名(admin,不需要存在)运行,用户名为“admin”,密码为“password”,角色为“ROLE_ADMIN”:
mvc = MockMvcBuilders
.webAppContextSetup(context)
.defaultRequest(get("/").with(user("user").roles("ADMIN")))
.apply(springSecurity())
.build();

If you find you are using the same user in many of your tests, it is recommended to move the user to a method. For example, you can specify the following in your own class named CustomSecurityMockMvcRequestPostProcessors:

如果您发现在许多测试中使用的是同一个用户,建议将用户移动到某个方法。例如,您可以在自己的名为CustomSecurityMockMvcRequestPostProcessors的类中指定以下内容:
public static RequestPostProcessor rob() {
return user("rob").roles("ADMIN");
}

Now you can perform a static import on SecurityMockMvcRequestPostProcessors and use that within your tests:

现在,您可以在SecurityMockMvcRequestPostProcessors上执行静态导入,并在测试中使用它:
 
import static sample.CustomSecurityMockMvcRequestPostProcessors.*;

...

mvc
.perform(get("/").with(rob()))

Running as a User in Spring MVC Test with Annotations

在带有注释的Spring MVC测试中作为用户运行
 
As an alternative to using a RequestPostProcessor to create your user, you can use annotations described in Chapter 11, Testing Method Security. For example, the following will run the test with the user with username "user", password "password", and role "ROLE_USER":
作为使用RequestPostProcessor创建用户的替代方法,您可以使用第11章测试方法安全性中描述的注释。例如,以下将使用用户名“user”,密码“password”和角色“ROLE_USER”运行测试:
@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/"))
...
}

Alternatively, the following will run the test with the user with username "user", password "password", and role "ROLE_ADMIN":

或者,以下将使用用户名“user”,密码“password”和角色“ROLE_ADMIN”运行测试:
@Test
@WithMockUser(roles="ADMIN")
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/"))
...
}

12.2.4 Testing HTTP Basic Authentication

While it has always been possible to authenticate with HTTP Basic, it was a bit tedious to remember the header name, format, and encode the values. Now this can be done using Spring Security’s httpBasic RequestPostProcessor. For example, the snippet below:

虽然始终可以使用HTTP Basic进行身份验证,但记住标题名称,格式和编码值有点乏味。现在可以使用Spring Security的httpBasic RequestPostProcessor来完成。例如,下面的代码段:
mvc.perform(get("/").with(httpBasic("user","password")))

will attempt to use HTTP Basic to authenticate a user with the username "user" and the password "password" by ensuring the following header is populated on the HTTP Request:

将通过确保在HTTP请求上填充以下标头,尝试使用HTTP Basic使用用户名“user”和密码“password”对用户进行身份验证:
Authorization: Basic dXNlcjpwYXNzd29yZA==

12.3 SecurityMockMvcRequestBuilders

Spring MVC Test also provides a RequestBuilder interface that can be used to create the MockHttpServletRequest used in your test. Spring Security provides a few RequestBuilder implementations that can be used to make testing easier. In order to use Spring Security’s RequestBuilder implementations ensure the following static import is used:

Spring MVC Test还提供了一个RequestBuilder接口,可用于创建测试中使用的MockHttpServletRequest。 Spring Security提供了一些RequestBuilder实现,可用于简化测试。为了使用Spring Security的RequestBuilder实现,请确保使用以下静态导入:
 
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.*;

  

12.3.1 Testing Form Based Authentication

You can easily create a request to test a form based authentication using Spring Security’s testing support. For example, the following will submit a POST to "/login" with the username "user", the password "password", and a valid CSRF token:

mvc.perform(formLogin())

It is easy to customize the request. For example, the following will submit a POST to "/auth" with the username "admin", the password "pass", and a valid CSRF token:

可以轻松自定义请求。例如,以下内容将使用用户名“admin”,密码“pass”和有效的CSRF令牌向“/ auth”提交POST:
mvc.perform(formLogin("/auth").user("admin").password("pass"))

We can also customize the parameters names that the username and password are included on. For example, this is the above request modified to include the username on the HTTP parameter "u" and the password on the HTTP parameter "p".

我们还可以自定义包含用户名和密码的参数名称。例如,这是上面的请求被修改为包括HTTP参数“u”上的用户名和HTTP参数“p”上的密码。
mvc.perform(formLogin("/auth").user("u","admin").password("p","pass"))

12.3.2 Testing Logout

While fairly trivial using standard Spring MVC Test, you can use Spring Security’s testing support to make testing log out easier. For example, the following will submit a POST to "/logout" with a valid CSRF token:

虽然使用标准的Spring MVC测试相当简单,但您可以使用Spring Security的测试支持来简化测试注销。例如,以下内容将使用有效的CSRF令牌向“/ logout”提交POST:
 
mvc.perform(logout())

You can also customize the URL to post to. For example, the snippet below will submit a POST to "/signout" with a valid CSRF token:

您还可以自定义要发布到的URL。例如,下面的代码段将使用有效的CSRF令牌向“/ signout”提交POST:
mvc.perform(logout("/signout"))

12.4 SecurityMockMvcResultMatchers

At times it is desirable to make various security related assertions about a request. To accommodate this need, Spring Security Test support implements Spring MVC Test’s ResultMatcher interface. In order to use Spring Security’s ResultMatcher implementations ensure the following static import is used:

有时希望对请求做出各种与安全相关的断言。为了满足这种需求,Spring Security Test支持实现了Spring MVC Test的ResultMatcher接口。为了使用Spring Security的ResultMatcher实现,请确保使用以下静态导入:
mvc
.perform(formLogin().password("invalid"))
.andExpect(unauthenticated());

12.4.2 Authenticated Assertion

It is often times that we must assert that an authenticated user exists. For example, we may want to verify that we authenticated successfully. We could verify that a form based login was successful with the following snippet of code:

通常我们必须断言经过身份验证的用户存在。例如,我们可能想验证我们是否已成功验证。我们可以使用以下代码片段验证基于表单的登录是否成功:
mvc
.perform(formLogin())
.andExpect(authenticated());

If we wanted to assert the roles of the user, we could refine our previous code as shown below:

如果我们想要断言用户的角色,我们可以优化我们之前的代码,如下所示:
mvc
.perform(formLogin().user("admin"))
.andExpect(authenticated().withRoles("USER","ADMIN"));

Alternatively, we could verify the username:

或者,我们可以验证用户名:
mvc
.perform(formLogin().user("admin"))
.andExpect(authenticated().withUsername("admin"));

We can also combine the assertions:

mvc
.perform(formLogin().user("admin").roles("USER","ADMIN"))
.andExpect(authenticated().withUsername("admin"));

Spring Security(三十六):12. Spring MVC Test Integration的更多相关文章

  1. Spring Security(十六):5.7 Multiple HttpSecurity

    We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. T ...

  2. spring boot / cloud (十六) 分布式ID生成服务

    spring boot / cloud (十六) 分布式ID生成服务 在几乎所有的分布式系统或者采用了分库/分表设计的系统中,几乎都会需要生成数据的唯一标识ID的需求, 常规做法,是使用数据库中的自动 ...

  3. Gradle 1.12用户指南翻译——第三十六章. Sonar Runner 插件

    本文由CSDN博客万一博主翻译,其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Githu ...

  4. Spring Security(十二):5. Java Configuration

    General support for Java Configuration was added to Spring Framework in Spring 3.1. Since Spring Sec ...

  5. Spring Security(三) —— 核心配置解读

    摘要: 原创出处 https://www.cnkirito.moe/spring-security-3/ 「老徐」欢迎转载,保留摘要,谢谢! 3 核心配置解读 上一篇文章<Spring Secu ...

  6. Spring Security(十):3. What’s New in Spring Security 4.2 (新功能)

    Among other things, Spring Security 4.2 brings early support for Spring Framework 5. You can find th ...

  7. 程序员编程艺术第三十六~三十七章、搜索智能提示suggestion,附近点搜索

    第三十六~三十七章.搜索智能提示suggestion,附近地点搜索 作者:July.致谢:caopengcs.胡果果.时间:二零一三年九月七日. 题记 写博的近三年,整理了太多太多的笔试面试题,如微软 ...

  8. centos shell脚本编程2 if 判断 case判断 shell脚本中的循环 for while shell中的函数 break continue test 命令 第三十六节课

    centos  shell脚本编程2 if 判断  case判断   shell脚本中的循环  for   while   shell中的函数  break  continue  test 命令   ...

  9. Spring Boot 2.X(六):Spring Boot 集成Redis

    Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...

随机推荐

  1. C#3.0智能的编译器

    智能的编译器 在C#3.0中,编译器变的越来越智能,我们不用提供给它完整的信息,仅需要提供必要的信息,编译器就可以进行推断为我们补全未提供的信息 自动实现的属性 在之前我们生成一个类时需要有一个字段, ...

  2. springboot+mybatis+dubbo+aop日志第一篇

    本篇文章主要讲述项目搭建过程,不会涉及过多的基础知识,本项目是作者对前段时间学习的一个总结,主要使用到技术有:maven父子工程.springboot.mybatis.dubbo.zookeeper. ...

  3. Java开发知识之Java的正则表达式

    目录 正则表达式 一丶什么是正则表达式 1.正则表达式简介 2.无正则表达式判断代码 3.使用正则表达式代码. 二丶正则表达式API 三丶正则表达式语法格式 1.正则表达式语法 正则表达式 一丶什么是 ...

  4. .NET快速信息化系统开发框架 V3.2 -> Web 用户管理模块编辑界面-组织机构选择支持级联选择

    下拉框级联选择功能非常的实用,框架用户管理编辑界面对组织机构的选择在3.2版本中新增了级联选择的支持,让组织机构的选择更加的方便与高效,也不容易出错. 我们框架的组织机构结合实际分成了5种类型,分别为 ...

  5. 理解 docker 容器中的 uid 和 gid

    默认情况下,容器中的进程以 root 用户权限运行,并且这个 root 用户和宿主机中的 root 是同一个用户.听起来是不是很可怕,因为这就意味着一旦容器中的进程有了适当的机会,它就可以控制宿主机上 ...

  6. SSH隧道:端口转发功能详解

    SSH系列文章: SSH基础:SSH和SSH服务 SSH转发代理:ssh-agent用法详解 SSH隧道:端口转发功能详解 1.1 ssh安全隧道(一):本地端口转发 如下图,假如host3和host ...

  7. Java开发笔记(二十八)布尔包装类型

    前面介绍了数值包装类型,因为不管是整数还是小数,它们的运算操作都是类似的,所以只要学会了Integer的用法,其它数值包装类型即可一并掌握.但是对于布尔类型boolean来说,该类型定义的是“true ...

  8. Java开发笔记(七十九)利用反射技术操作私有属性

    早在介绍多态的时候,曾经提到公鸡实例的性别属性可能被篡改为雌性,不过面向对象的三大特性包含了封装.继承和多态,只要把性别属性设置为private私有级别,也不提供setSex这样的性别修改方法,那么性 ...

  9. Python进阶之模块

    在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很 ...

  10. Messenger在MVVM模式中的应用

    Messenger在MVVM模式中的应用 Messenger在MVVM中应用的前提 我们知道在MVVM架构中,系统平台的Silverlight客户端界面开发和业务逻辑已经被分开,XAML是SL的主要部 ...