我需要测试一些受保护的 url,因此我需要在我的测试(junit)中设置一个模拟安全上下文。
特别是我需要使用经过身份验证的用户对我的 Web 应用程序执行一些获取和发布。下面是我的代码,我可以创建这样的安全上下文,但我需要将它注入到“MockMvc”对象中。
我在安全上下文中设置了身份验证对象并且它起作用了,'SecurityContextHolder.getContext().getAuthentication().getPrincipal()' 的输出结果是 chanelle.evans@616747.com 但是当我在 /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("chanelle.evans@616747.com");
userDetailsImp.setEmail("chanelle.evans@616747.com");
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
}
我想我应该将我的身份验证对象放在 MockMvc 对象中,但我不知道如何
有人知道吗?