使用WebSocket连接被Spring Security拦截

发布时间:2022-05-27 09:58

最近项目中使用Spring Security进行验证过滤,后来发现Spring Security拦截http的同时也拦截了websocket,导致websocket无法连接!

void configure(WebSecurity webSecurity)中设置即可:

@Override
public void configure(WebSecurity webSecurity){
webSecurity.ignoring().antMatchers(
"/ws/**"
);
}

完整代码

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailService;
@Autowired
private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
@Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//super.configure(http);
// TODO Auto-generated method stub
httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf
.disable()
//		.sessionManagement()// 基于token,所以不需要session
//		.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//		.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
"/",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/***/**/*.html",
"/***/**/*.css",
"/***/**/*.js",
"/swagger-resources/**",
"/v2/api-docs/**",
"/**/FAQ",
"/**/pmq/public"
)
.permitAll()
.antMatchers("/user/login", "/task/optional_data_info")// 对登录注册要允许匿名访问
.permitAll()
.antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
.permitAll()
//.antMatchers("/**")//测试时全部运行访问
//.permitAll()
.anyRequest()// 除上面外的所有请求全部需要鉴权认证
.authenticated();
// 禁用缓存
httpSecurity.headers().cacheControl();
// 添加JWT filter
httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
//添加自定义未授权和未登录结果返回
httpSecurity.exceptionHandling()
.accessDeniedHandler(restfulAccessDeniedHandler)
.authenticationEntryPoint(restAuthenticationEntryPoint);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}
//忽略websocket拦截
@Override
public void configure(WebSecurity webSecurity){
webSecurity.ignoring().antMatchers(
"/ws/**"
);
}
@Bean
public UserDetailsService userDetailsService()
{
return new PhotovoltaicUserDetailsService();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
return new JwtAuthenticationTokenFilter();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}

文档下载:使用WebSocket连接被Spring Security拦截.doc文档

THE END
喜欢就支持一下吧