gpt4 book ai didi

java - 用于 Selenium 测试的 Spring Security @WithMockUser

转载 作者:行者123 更新时间:2023-11-30 08:52:51 27 4
gpt4 key购买 nike

我刚刚发现了新的 Spring Security 4 测试注释 @WithMockUser,但我无法让它用于我的 Selenium 测试。问题是,这个注解创建了一个模拟的 SecurityContext,但是一个新的是由 HttpSessionSecurityContextRepository 创建的,因为 Selenium 基于真实的浏览器运行测试。我能否以某种方式告诉 Spring 使用模拟 SecurityContext 作为下一个 session 安全上下文?

谢谢!

最佳答案

我找到了使用测试类路径中的新过滤器对模拟用户进行身份验证的方法:

@Component
public class MockUserFilter extends GenericFilterBean {

@Autowired
private UserDetailsService userDetailsService;

private SecurityContext securityContext;

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (securityContext != null) {
SecurityContextRepository securityContextRepository = WebTestUtils.getSecurityContextRepository(request);

HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response);
securityContextRepository.loadContext(requestResponseHolder);

request = requestResponseHolder.getRequest();
response = requestResponseHolder.getResponse();

securityContextRepository.saveContext(securityContext, request, response);

securityContext = null;
}
chain.doFilter(request, response);
}

public void authenticateNextRequestAs(String username) {
UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(authentication);
}
}

它的灵感来自 SecurityMockMvcRequestPostProcessorsWithUserDetailsS​​ecurityContextFactory

我无法使用 @WithUserDetails 注释,因为我运行 Cucumber 测试,但使用此过滤器,我可以在一行中为下一个请求模拟身份验证:testSecurityFilter.authenticateNextRequestAs("username");

关于java - 用于 Selenium 测试的 Spring Security @WithMockUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034761/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com