【发布时间】:2017-12-27 17:39:54
【问题描述】:
我正在使用 Spring Boot 创建一个后端,并且刚刚添加了 JWT 安全性。
我已经使用 REST 客户端进行了一些测试,并且 JWT 安全性工作正常,但是我的所有单元测试现在都返回 403 错误代码。
我已经为它们添加了@WithMockUser 注释,但它们仍然不起作用:
@Test
@WithMockUser
public void shouldRedirectToInstaAuthPage() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/instaAuth")).andExpect(status().is3xxRedirection());
}
这里有没有我遗漏的其他配置?
这里是安全配置:
@Configuration
@EnableWebSecurity
public class ServerSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated()
.and()
// We filter the api/login requests
.addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
// And filter other requests to check the presence of JWT in header
.addFilterBefore(new JWTAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// Create a default account
auth.inMemoryAuthentication()
.withUser("john")
.password("123")
.roles("ADMIN");
}
}
和方法安全性:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
【问题讨论】:
-
看看这个以前的answer 到一个类似的问题。
-
嗨@punkrocker27ka,感谢您的回复。在那篇文章中,问题出在 Oauth2 身份验证配置上,但我使用的是 JWT,所以我没有资源服务器。
-
它们不是相互排斥的。如果可能的话,你能在 GitHub 上分享一个最小的示例项目吗?这样可以更轻松地进行故障排除。
-
好的,让我尝试按照他们在该主题上的建议进行操作。我也会尝试在 GitHub 上上传一些东西。
-
嗨,我自己生成了 JWT 令牌并添加到测试中,现在一切正常。我希望我在这里没有做坏事。我将发布一个包含详细信息的答案。
标签: java spring unit-testing spring-boot jwt