Java Spring安全中的登录测试
我刚开始使用Spring引导和基于Java的Spring配置,在尝试测试安全相关方法(如登录和注销)时遇到了问题 我的项目中有以下配置 SecurityConfig.java:Java Spring安全中的登录测试,java,spring-boot,spring-security,spring-test,Java,Spring Boot,Spring Security,Spring Test,我刚开始使用Spring引导和基于Java的Spring配置,在尝试测试安全相关方法(如登录和注销)时遇到了问题 我的项目中有以下配置 SecurityConfig.java: @EnableWebSecurity @Configuration @EnableGlobalMethodSecurity(prePostEnabled=true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Overri
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint())
.and()
.formLogin()
.successHandler(authenticationSuccessHandler())
.failureHandler(authenticationFailureHandler())
.and()
.logout()
.and()
.authorizeRequests()
.antMatchers("/login", "j_spring_security_check", "/register", "/logout").permitAll()
.antMatchers("/**").hasRole("USER");
}
@Autowired
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("guest").password("guest").roles("USER");
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return new RestAuthenticationSuccessHandler();
}
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return new SimpleUrlAuthenticationFailureHandler();
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
return new RestAuthenticationEntryPoint();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
SecurityWebAppInitializer.java
@Order(1)
public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer { }
RestAuthenticationSuccessHandler.java
public class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
clearAuthenticationAttributes(request);
return;
}
String targetUrlParam = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl() ||
(targetUrlParam != null &&
StringUtils.hasText(request.getParameter(targetUrlParam)))) {
requestCache.removeRequest(request, response);
clearAuthenticationAttributes(request);
return;
}
clearAuthenticationAttributes(request);
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
}
现在,我想测试登录过程,因此我的测试类如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SecurityWebAppInitializer.class, SecurityConfig.class })
public class SecurityTests {
private MockMvc mockMvc;
@Autowired
private FilterChainProxy filterChainProxy;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(SecurityWebAppInitializer.class, SecurityConfig.class).addFilters(filterChainProxy).build();
}
@Test
public void thatLoginWithCorrectCredentialsWorks() throws Exception {
mockMvc.perform(post("/j_spring_security_check")
.param("j_username", "guest")
.param("j_password", "guest")
).andExpect(status().isOk());
}
}
上述测试返回以下错误
java.lang.AssertionError: Status
Expected :200
Actual :403
这表示用户被禁止访问登录页面。但是,我不明白为什么我在SpringConfig中配置了具有上述凭据的用户可以登录到我的应用程序。如果我的问题很愚蠢,我想提前道歉,但我仍在努力提高我对该框架的了解,因为我只使用了几个星期
编辑:当我使用CURL登录时,出现以下错误:
{“时间戳”:1401633376720,“错误”:“禁止”,“状态”:403,“消息”:“未找到预期的CSRF令牌。会话是否已过期?”}
您是否尝试过使用
.perform(post(…).with(csrf()
)运行?就像在“否”中建议的那样,我没有,但我觉得它很有帮助!非常感谢!