当前位置: 首页 > 知识库问答 >
问题:

CORS错误:Spring Boot Multiple WebSecurity配置适配器

章绪
2023-03-14

我的代码中有多个WebSecurity配置适配器:

@Configuration
@Order(1)
public class BoardSecurityConf extends WebSecurityConfigurerAdapter {
    private final X509BoardDetailsService x509BoardDetailsService;

    public BoardSecurityConf(X509BoardDetailsService x509BoardDetailsService) {
        this.x509BoardDetailsService = x509BoardDetailsService;
    }




    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/board/**")
                .and()
                .authorizeRequests()
                .antMatchers("/board/all")
                .authenticated()
                .anyRequest()
                .permitAll()
                .and()
                .x509()
                .subjectPrincipalRegex("CN=(.*?)(?:,|$)")
                .userDetailsService(x509BoardDetailsService);
    }
}
@Configuration
@Order(2)
public class UserSecurityConf extends WebSecurityConfigurerAdapter {

    private final JwtRequestFilter jwtRequestFilter;
    private final JwtUserDetailsService jwtUserDetailsService;

    public UserSecurityConf(JwtRequestFilter jwtRequestFilter, JwtUserDetailsService jwtUserDetailsService) {
        this.jwtRequestFilter = jwtRequestFilter;
        this.jwtUserDetailsService = jwtUserDetailsService;
    }

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

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/user/**")
                .and()
                .authorizeRequests()
                .antMatchers("/user/authenticate")
                .permitAll()
                .antMatchers(HttpMethod.POST, "/user")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint())
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }


    @Bean
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint() {
        return new JwtAuthenticationEntryPoint();
    }
}

@EnableWebSecurity
@Order(3)
public class SecurityConf extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and()
                .csrf()
                .disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

当我从ajax请求访问我的站点时,我得到:从源http://localhost:8082访问http://localhost:8080/user/authenticate的XMLHttpRequest已被CORS策略阻止:对飞行前请求的响应未通过权限改造检查:请求的资源上不存在访问控制允许源标头。

我想我的WebSecurity配置适配器中有一些配置错误。已经检查了Spring文档,但找不到关于cors和多个WebSecurity配置适配器配置的任何信息

@编辑:

现在我得到了这个例外:


java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
    at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:473) ~[spring-web-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:532) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1261) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1043) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.58.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.16.jar:5.3.16]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.58.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.58.jar:9.0.58]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]

共有1个答案

雷曜灿
2023-03-14

我修复了这个问题。显然,我用作STOMP客户端的libarySockJS在其XHR中将与凭据标志设置为true(参见问题)。设置此标志时,您不允许在Cors上使用通配符作为AlloweOrigin。

因此,我改变了:

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

对此:

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8082", "https://localhost:8082"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

我还添加了. cors(with Defaault())到每个WebSecurityConfigrerAdapter,它会自动使用我来自corsConfigurationSource()的bean,请参阅此处

 类似资料:
  • 版本介绍 百度移动统计提供两种版本的Crash错误统计功能:标准版、详细Crash版。 标准版:采集的Crash日志内容较少,包含关键的LastBacktrace等信息。 详细Crash版:采集的Crash日志内容丰富,接近iOS系统完整的Crash格式,包含LastBacktrace、thread等信息。 由于加入详细的Crash统计功能会使SDK的体积增大,所以请结合自身业务场景,合理选择SD

  • 百度移动统计提供了错误统计功能。包括错误报告,错误路径等。 由于加入详细的错误统计上报功能,会导致SDK的整体大小变大。故我们针对那些只需要基本的错误次数统计功能的用户提供了标准的java错误统计功能,集成在了应用分析(无埋点)和应用分析(手动埋点)SDK中;针对需要native crash错误信息的用户,提供了附加的Crash版本。

  • 我有一个对我的Rest Webservice的AJAX请求,带有一个自定义头“login”。 用户代理:Mozilla/5.0(Windows NT 10.0;Win64;x64;RV:58.0)Gecko/20100101 Firefox/58.0 接受:text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 接受语言:fr,f

  • 我有Spring引导Rest应用程序。最近,我使用JSONWebToken实现了用户身份验证。 JWTauthFilter: 我的登录控制器有一个映射“/token”,所有其他控制器都映射为“/rest/**”。有趣的是,调用一个“/token”控制器可以很好地工作...它返回令牌和用户详细信息。服务器响应包含: access-control-allow-credentials为true acce

  • 我正在尝试启动我的hadoop应用程序,但是在启动时我在日志文件中看到了这一点,有没有人知道问题是什么? 正在为HDFS创建文件系统://10.170.4.141:9000 java.io.ioException:config()在org.apache.hadoop.conf.configuration(configuration.java:229)在org.apache.hadoop.conf.

  • 我有一个JSON: 我创建了以下pojo 在我的控制器中,我有一个@PostMapping方法,我尝试检索DocumentToSignRestRequest: 并使用模型映射器将其传递给DocumentDto类:DocumentDto DocumentDto=ModelMapper。地图(documentToSignRestRequest,DocumentDto.class); 这个类的不同属性与