使用 JWT 令牌安全性进行春季启动单元测试
2022-09-01 08:51:40
我正在使用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();
}
}