如何在 Spring MVC 中 Mock 安全上下文进行测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18270973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:09:33  来源:igfitidea点击:

How to Mock the security context in Spring MVC for testing

springspring-mvcjunitspring-securityspring-test-mvc

提问by cloudy_weather

I need to test some protected urls, therefore I need to set up a mock security context in my tests (junit).
In particular I need perform some gets and post against my web application, using an authenticated user. Below there is my code, I am able to create a such security context but I need to inject it in the 'MockMvc' object.
I set the authentication object in the security context and it works, the output result of 'SecurityContextHolder.getContext().getAuthentication().getPrincipal()' is [email protected] but when I call the GET on /profile I have an assertion error because I am redirected to my login page, and not to /profile.

我需要测试一些受保护的 url,因此我需要在我的测试 (junit) 中设置一个模拟安全上下文。
特别是我需要使用经过身份验证的用户对我的 Web 应用程序执行一些获取和发布操作。下面是我的代码,我能够创建这样的安全上下文,但我需要将它注入到“MockMvc”对象中。
我在安全上下文中设置了身份验证对象并且它工作正常,'SecurityContextHolder.getContext().getAuthentication().getPrincipal()' 的输出结果是 [email protected] 但是当我在 /profile 上调用 GET 我有一个断言错误,因为我被重定向到我的登录页面,而不是 /profile。

@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:spring/security.xml", "classpath:spring/view.xml"})
@ActiveProfiles("default")
@RunWith(SpringJUnit4ClassRunner.class)
public class AuthenticationTest {

@Autowired
WebApplicationContext ctx;

private MockMvc mockMvc;

@Autowired
private FilterChainProxy springSecurityFilterChain;

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(ctx).addFilters(springSecurityFilterChain).build();

    //@formatter:off

    UserDetailsLogic userDetailsLogic = null;
    userDetailsLogic = ctx.getBean(UserDetailsLogic.class);
    final UserDetailsImp userDetailsImp = new UserDetailsImp();
    userDetailsImp.setAccountId(1001);
    userDetailsImp.setUserId(8001);
    userDetailsImp.setPassword("a378c92df7531df6fdf351f7ae1713f91f2dd2d45b9c6e1a8b02736ee3afec6595ff60465e9cb8da");
    userDetailsImp.setUsername("[email protected]");
    userDetailsImp.setEmail("[email protected]");

    final Collection<GrantedAuthorityImplementation> authorities= new ArrayList<GrantedAuthorityImplementation>();
    authorities.add(new GrantedAuthorityImplementation("ROLE_USER"));

    userDetailsImp.setAuthorities(authorities);

    userDetailsImp.setAccountNonExpired(true);
    userDetailsImp.setAccountNonLocked(true);
    userDetailsImp.setCredentialsNonExpired(true);
    userDetailsImp.setEnabled(true);

    final Authentication authToken = new UsernamePasswordAuthenticationToken (userDetailsImp.getUsername(), userDetailsImp.getPassword(), userDetailsImp.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authToken);

    System.out.println("principal:"+SecurityContextHolder.getContext().getAuthentication().getPrincipal());      
    mockMvc.perform(get("/profile").principal(authToken)

            .contentType(MediaType.TEXT_HTML)

            .accept(MediaType.TEXT_HTML))

            .andDo(print())

            .andExpect(status().isOk())
            .andExpect(redirectedUrl(null))
            .andExpect(forwardedUrl(null));
    //@formatter:on     
}

I guess that I should put my authentication object inside the MockMvc object, but I do not know how
Does anyone have any idea?

我想我应该将我的身份验证对象放在 MockMvc 对象中,但我不知道如何
有人知道吗?

采纳答案by Emanuele Ivaldi

This is something I wrote few days ago. I think that could be helpful (I tested the same thing against the login form, using the session for the second request) see loginUser1Ok(..))

这是我前几天写的。我认为这可能会有所帮助(我针对登录表单测试了相同的内容,使用会话进行第二个请求)请参阅 loginUser1Ok(..))

See MvcTest.javain

参见MvcTest.java

m4nuv/easy-bank.

m4nuv/easy-bank

回答by Grigory Kislin

Add in pom.xml

在 pom.xml 中添加

<repository>
    <id>spring-snaspho</id>
    <url>http://repo.springsource.org/libs-milestone/</url>
</repository>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <version>4.0.0.M1</version>
</dependency>

and use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessorsfor authorization request. See the sample usage here, and Spring.io jira ticket SEC-2592.

org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors用于授权请求。请参阅此处的示例用法Spring.io jira 票证 SEC-2592