Spring Security 和 Websocket 的 CORS 问题

问题描述 投票:0回答:2

我正在开发一个基于 Spring 后端的 Ionic 应用程序。 我使用 JWT 身份验证实现了 Spring Security。我的应用程序将有一个聊天室,用户可以在其中进行私人或公共聊天。因此,我正在实现一个 WebSocket 系统,以便实时获取所有更新。

这是我的安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    private AuthenticationManager authenticationManager;

    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(this.userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
        return new JwtAuthenticationTokenFilter();
    }

   // configurazione Cors per poter consumare le api restful con richieste ajax
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");
        configuration.setAllowedMethods(Arrays.asList("POST, PUT, GET, OPTIONS, DELETE"));
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
         httpSecurity
         .csrf().disable()
         .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
         .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
         .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().cors().and()
         .authorizeRequests()
         .antMatchers(
                 HttpMethod.GET,
                 "/",
                 "/*.html",
                 "/favicon.ico",
                 "/**/*.html",
                 "/**/*.css",
                 "/**/*.js",
                 "/image/**").permitAll()
         .antMatchers("/socket/**").permitAll()
         .antMatchers("/public/**").permitAll().and()
         .authorizeRequests().anyRequest().authenticated().and();

         httpSecurity.headers().cacheControl();
    }

    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
        return authenticationManager();
    }
}

这是我的 WebSocket 配置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer{
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/socket")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/chat")
                .enableSimpleBroker("/subscribe");
    }
}

在这种情况下,我目前面临这个错误:

访问 XMLHttpRequest 'http://localhost:8080/SpringApp/socket/info?t=1547732425329' 来自 来源 'http://localhost:8100' 已被 CORS 策略阻止: 响应中“Access-Control-Allow-Origin”标头的值必须 当请求的凭据模式为时,不能是通配符“*” '包括'。发起请求的凭证模式 XMLHttpRequest 由 withCredentials 属性控制。

每个调用都可以工作(我已通过 jwt 完全授权),但 WebSocket 无法工作。

因此,我尝试简单地删除安全配置类中配置方法中的 .cors() 。这导致我遇到了一个相反的问题:

error in chrome

确实,现在 WebSocket 工作完美,而不是每个 api 调用都给我 401。

解决这个问题的正确方法是什么? 谢谢你

spring security websocket cors
2个回答
0
投票

是的,当我在一个项目中解决相关问题时,我遇到了同样的错误。解决方案是我必须将 allowed-origin 标头值设置为我的应用程序的 URL。如果您发送凭据,则不允许使用通配符值 (*)。


0
投票

这个案子解决了吗?我也有同样的问题。

© www.soinside.com 2019 - 2024. All rights reserved.