Spring Security(三十六):12. Spring MVC Test Integration
Spring Security provides comprehensive integration with 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’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 {@Autowiredprivate WebApplicationContext context;private MockMvc mvc;@Beforepublic 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
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:
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:
mvc.perform(post("/").with(csrf()))
If you like you can include CSRF token in the header instead:
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:
- Running as a User in Spring MVC Test with RequestPostProcessor
- 使用RequestPostProcessor在Spring MVC Test中作为用户运行
- Running as a User in Spring MVC Test with Annotations
- 在带有注释的Spring MVC测试中作为用户运行
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":
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:
- Invoking apply(springSecurity())
- Adding Spring Security’s
FilterChainProxy
toMockMvc
- Manually adding
SecurityContextPersistenceFilter
to theMockMvc
instance may make sense when usingMockMvcBuilders.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".
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
:
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.
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:
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":
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
:
public static RequestPostProcessor rob() {return user("rob").roles("ADMIN");
}
Now you can perform a static import on SecurityMockMvcRequestPostProcessors
and use that within your tests:
import static sample.CustomSecurityMockMvcRequestPostProcessors.*;...mvc.perform(get("/").with(rob()))
Running as a User in Spring MVC Test with Annotations
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":
@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":
@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:
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:
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:
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:
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".
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:
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:
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:
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"));
转载于:https://www.cnblogs.com/shuaiandjun/p/10146613.html
Spring Security(三十六):12. Spring MVC Test Integration相关推荐
- Spring Boot教程(十六):Spring Boot集成shiro
Apache Shiro™是一个功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理.借助Shiro易于理解的API,您可以快速轻松地保护任何应用程序 - 从最小的移动应用程序到 ...
- 《深入理解 Spring Cloud 与微服务构建》第十六章 Spring Boot Security 详解
<深入理解 Spring Cloud 与微服务构建>第十六章 Spring Boot Security 详解 文章目录 <深入理解 Spring Cloud 与微服务构建>第十 ...
- spring boot 与 iview 前后端分离架构之开发环境基于docker的部署的实现(三十六)
spring boot 与 iview 前后端分离架构之开发环境基于docker的后端的部署的实现(三十六) 公众号 基于docker的后端的部署 安装mysql数据库 创建数据库 安装redis 安 ...
- 精选Spring Boot三十五道必知必会知识点!
Spring Boot 是微服务中最好的 Java 框架. 我们建议你能够成为一名 Spring Boot 的专家.本文精选了三十五个常见的Spring Boot知识点,祝你一臂之力! 问题一 Spr ...
- 【OAuth2】十六、Spring Authorization Server如何生成并发放token的
这里写目录标题 前言 一.OAuth2TokenEndpointConfigurer 1.关于authenticationProvider和authenticationProviders自定义的注意 ...
- Spring Security 源码分析:Spring Security 授权过程
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring I ...
- 三十六進制之間隨便轉換
去年在網上給一家公司投簡歷的時候,對方要求寫一個任意進制轉換的函數,當時沒有回過神來,也不知道JAVA中有這樣的函數,呵呵.于是就自己操刀,寫了這個三十六進制之音隨便轉的函數.不過,權當練習吧,如果你 ...
- 避暑山庄消失的三十六景,曾经那么美!
来源: 老家热河 过去 老家热河曾先后推出了几篇 承德人李树介绍避暑山庄的文章 图文并茂,知识性强 受到很多读者朋友的欢迎 今天 李树又为我们带来了 避暑山庄遗存三十六景 一起看看都是哪里吧 避暑山庄 ...
- 【正点原子FPGA连载】第三十六章 基于OV5640的PL以太网视频传输实验-摘自【正点原子】领航者ZYNQ之FPGA开发指南_V2.0
1)实验平台:正点原子领航者ZYNQ开发板 2)平台购买地址:https://item.taobao.com/item.htm?&id=606160108761 3)全套实验源码+手册+视频下 ...
最新文章
- 为什么你问问题,别人都已读不回?
- 第十六届智能车竞赛视觉AI组相关议题讨论
- 怀旧服湖畔镇服务器位置,《魔兽世界怀旧服》今天再开10组新服 47组服务器免费转服开启...
- 笔趣看小说全部章节爬取实战
- CV报错:CAP_IMAGES: can‘t find starting number (in the name of file): x in function ‘icvExtractPattern‘
- redis linux无法启动服务,CentOS7 下redis不能开机启动,求解?
- WCF学习之旅—WCF概述(四)
- chatterbot mysql_ChatterBot代码解读-介绍和框架
- 微信小程序云开发教程-微信小程序的JSON配置
- cuda_error_launch_failed: unspecified launch failure
- 12个偏微分方程常用的不等式
- 计算机无法正常更新,电脑时间不能自动更新怎么回事?电脑时间校准同步方法介绍...
- 生成3D多棱柱的方法(3D立体图片)
- Windows编程之虚拟桌面实现原理
- 小迪安全第10天 信息收集,资产监控拓展
- js鼠标单击和双击事件
- vue中用js将json数据按英文字母顺序进行排序
- 安装完搜狗输入法发现输出的是繁体字。
- GIS领域常用软件工具(框架)介绍与推荐
- 星球福利 | 读书的季节,送上豆瓣 Top10 区块链书单
热门文章
- linux用户开机.bashrc,验证linux shell在启动时会自动执行用户主目录下的.bashrc脚本...
- web优化之-asp.net js延迟加载 js动态合并 js动态压缩
- OSCache操作详解+标签使用
- 微软:四种方法暂时屏蔽IE最新漏洞
- 传感器 倾斜角 android,android – 如何使用sensor / s获得手机的角度/度数?
- Android4.4点击无响应,webview某些超链接点击无响应的问题
- 关于power shell
- fedora core 7下如何安装Fcitx小企鹅输入法
- tensor转换为图片_pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换
- request对象_爬虫:request库的简介