【问题标题】:Spring erro Cors弹簧误差
【发布时间】:2021-10-31 06:05:39
【问题描述】:

我的弹簧 Cors 有问题。

我在 chome 上收到此错误: CORS 策略已阻止从源“http://localhost:8080/api/informationWS”访问 XMLHttpRequest:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。

我的文件 WebSecurityConfigurerAdapter

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {   
    @Autowired
    private LoginService loginService;
    
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }   
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {   
        auth
            .userDetailsService(loginService)
            .passwordEncoder(this.passwordEncoderAutentication());
    }
    
    @Bean
    public PasswordEncoder passwordEncoderAutentication() {
        String idForEncode = "bcrypt";
        Map<String, PasswordEncoder> encoders = new HashMap<>();
        encoders.put(idForEncode, new BCryptPasswordEncoder());
        encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
        encoders.put("scrypt", new SCryptPasswordEncoder());
         
        PasswordEncoder passwordEncoder = new DelegatingPasswordEncoder(idForEncode, encoders);
        
        return passwordEncoder;
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

我的文件 ResourceServerConfigurerAdapter

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/api/informationWS").permitAll()
            .antMatchers(HttpMethod.POST, "/api/work").authenticated()
            .anyRequest().denyAll();
    }  
}

我尝试通过以下两种方式使用 Cors,但它们都不起作用,产生相同的错误

我的档案

@Configuration
@EnableWebMvc
public class Cors implements WebMvcConfigurer {

   @Override
    public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**")
            .allowedOrigins("http://localhost:4200");
    }
}

我的文件 Cors2

@Configuration
public class Cors {

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterFilterRegistrationBean(){
        List<String> host = Arrays.asList("http://localhost:4200");

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(host);
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/api/**", corsConfiguration);

        CorsFilter corsFilter = new CorsFilter(source);
        FilterRegistrationBean<CorsFilter> filter = new FilterRegistrationBean<>(corsFilter);
        filter.setOrder(Ordered.HIGHEST_PRECEDENCE);

        return filter;
    }
}

【问题讨论】:

    标签: spring cors


    【解决方案1】:

    你可以尝试/检查什么:

    • 检查应用程序代码是否已执行 - 可能服务器因某种原因停止执行,因此您的 spring 代码无法添加标头。
    • 可能存在预检请求而服务器不允许(因此服务器再次停止执行,您的后端代码无法发送标头)
    • 也许您自己在添加标头之前在某处停止脚本,例如System.exit(0);
    • 可能存在重定向到不添加标头的代码,例如某些异常
    • 尝试运行来自 Postman 的请求 - 您应该不会收到错误消息,也许您会看到一些令人惊讶的东西。
    • 这个.antMatchers(HttpMethod.GET, "/api/informationWS") 真的符合请求吗?也许有一种方法可以添加通配符仅用于测试并查看它是否有效?您是否发送 GET 请求?

    更多细节,技术不同但概念相同:https://dariuscoder.com/2021/09/16/how-to-debug-cors/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-13
      • 2017-12-31
      • 2013-12-06
      • 2012-12-22
      • 2011-07-25
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多