我需要测试一些受保护的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对象中,但我不知道如何 有没有人有任何想法?
答案 0 :(得分:12)
答案 1 :(得分:3)
在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>
并使用org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors
进行授权请求。 See the sample usage here和Spring.io jira ticket SEC-2592。