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

Spring数据Rest中的CORS飞行前请求

拓拔烨赫
2023-03-14

我有一个Spring Boot/Spring Data REST服务,允许访问许多资源。其中一些资源(例如/detections)可以自由访问,其他资源(例如/users)需要基本的HTTP身份验证。通过使用CURL测试REST服务,所有工作都按预期进行。当我试图从Angular2 web应用程序访问服务时,问题就会出现。

this.http.get(this.DETECTIONS_API_ENDPOINT).subscribe(
                            response => {
                              ...
                            },
                            error => {
                              ...
                            }
                    );
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Basic ' + btoa(username+':'+password)); 

    return this.http.get(this.USERS_API_ENDPOINT, { body: "", headers: headers }).subscribe(
                            response => {
                              ...
                            },
                            error => {
                              ...
                            }
                    );
@Configuration
public class MyAppConfigurationSecurity extends WebSecurityConfigurerAdapter {

    private Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();

    @Autowired
    private UserDetailsService myAppUserService;

    /**
     * HttpSecurity URL configuration settings. Configure authentication necessary for POST but not for GET
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/detections").permitAll()
                .antMatchers(HttpMethod.GET, "/detections/search/findTop5ByOrderByTimestampDesc").permitAll()
                .antMatchers("/users").hasAuthority("ADMIN")
                .antMatchers("/roles").hasAuthority("ADMIN")
                .antMatchers("**").authenticated()
            .and().httpBasic().and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }


    /**
     * Sets custom MyAppUserService bean as user detail service
     */

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myAppUserService).passwordEncoder(md5PasswordEncoder);
    }

}
@Configuration
public class MyAppConfigurationCors {

    @Bean
    public CorsFilter corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // you USUALLY want this
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("OPTIONS"); // I added this in a second phase, but nothing changes
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

共有1个答案

穆正青
2023-03-14

关于如何集成CORS和Spring Security性,请参阅Spring文档。

必须首先处理COR:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
 类似资料:
  • 我使用AJAX请求通过POST将数据发送到另一个域。因为我的内容类型不是标准的(它是JSON格式),所以需要一个飞行前请求。(使用请求方法:选项) 如维基百科跨域XHR调用图表中所述 我想知道这是否很费时,因为浏览器将必须到达服务器两次或不?也许这取决于每个浏览器的行为? 通过使用内容类型“纯文本”来避免飞行前请求,我是否获得了一些时间?

  • 我有一个云函数,它在我的客户机上验证表单提交的输入。我正在使用云函数用于带有cors express中间件的Firebase https触发器。 Firebase功能 对函数的客户端调用 问题 是否可以防止firebase在预飞行请求上触发函数调用?如果没有,那么是否有一种方法可以阻止预飞行请求并成功地将数据传递给函数。

  • 所以这里的是一个类似JWT的标记。 在我的Angular代码中,我只需将令牌添加为,如下所示: 请注意,我的身份验证/注册路由工作正常,我只是在将标头传输到Spring服务器时遇到了困难。 谢谢,

  • 我使用的是JHIPSTERV2.27.2,我通过取消application.yml中的行注释来启用cors

  • 问题内容: 我现在奋斗了几个小时。我想向另一个域发出简单的Ajax请求,但始终出现http 401错误: 我在服务器端设置了所有相关的CORS标头。这是网络流量: 我知道有很多关于此主题的文章,但似乎我缺少一些简单的东西。有人可以帮我吗? 问题答案: 更新 看起来我不对。标头从不发送请求。 -你需要确保你的服务器不响应到请求。 我不知道您的服务器用什么语言编写,但是您以错误的方式实现了授权-应该从

  • 在调试我遇到的CORS问题时,我发现了以下行为。Chrome发出以下选项预检请求(由Chrome本身在CURL中重写): 以下情况下服务器对此请求的响应: 是响应“无效CORS请求”的主体。如果我重复该请求,删除标头“Access Control request Method”(仅该标头),则OPTIONS请求将成功,并得到以下响应: 然而,有问题的头是CORS规范标准头,所以它不应该阻止请求成功