如何允许所有域的CrossOrigin? [英] How to allow CrossOrigin from all domains?

查看:1028
本文介绍了如何允许所有域的CrossOrigin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使此端点允许从任何地方发出请求?

Is there anyway to make this end point allow request from anywhere?

我尝试过,但没有一个起作用。

I've tried like but none of them worked.


@CrossOrigin(origins =

@CrossOrigin(origins = http://



@CrossOrigin(origins = "http://localhost:3001")
@GetMapping(path="/transactions")
public @ResponseBody List<RealEstateTransaction> getTransactions() {
    return realEstateTransactionService.findTargets();
}


推荐答案

在使用跨域时,大多数情况下,我们倾向于担心什么&哪里出错了。在处理请求之前,需要在服务器端处理许多因素,包括安全性,Web组件,套接字等。在Spring Boot应用程序中实现 CORS 的方法很多。

While working with cross domains, most of the time we tend to worry about what & where it went wrong. There are many factors including security, web components, sockets, etc to be handled at the server side before a request is processed. Many ways to implement the CORS in the Spring Boot application.

通过实现 @CrossOrigin 就像在 Main 类中所做的一样。如果只能从特定域访问特定的API,也可以通过在特定的控制器/方法中添加 @CrossOrigin 来完成。

By implementing @CrossOrigin like what you did in the Main class. Also can be done by adding @CrossOrigin to specific controllers/methods, if particular API should be accessed only from specific domain.

@CrossOrigin("*") // to allow from all domains
@CrossOrigin("http://localhost:3001") // to allow from specific domain
@CrossOrigin(origins = "http://localhost:3001")


2。 WebConfig


如果Spring Application是MVC,则可以在其中访问资源。只需通过覆盖 WebMvcConfigurer的 addCorsMappings 函数来添加CORS映射。

2. WebConfig

If Spring Application is MVC where the resources could be accessed. Simply add the CORS mappings by overriding WebMvcConfigurer's addCorsMappings function.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*");
    }
}



  1. SecurityConfig
    在应用程序中启用安全性后,必须在 SecurityConfig 中实现CORS。注册CORS过滤器可以通过多种方式完成。一种是将 UrlBasedCorsConfigurationSource 添加到http.cors()函数。另一种方法是通过扩展 CorsFilter 来创建 CustomCorsFilter

  1. SecurityConfig When security is enabled in the application then CORS must be implementated in the SecurityConfig. Registering the CORS filter can be done in many ways. One is adding UrlBasedCorsConfigurationSource to the http.cors() function. Another is to create CustomCorsFilter by extending the CorsFilter.


public class CustomCorsFilter extends CorsFilter {

    public CustomCorsFilter() {
        super(configurationSource());
    }
    
    public static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.setMaxAge(3600L);
    
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", configuration);
        
        return corsConfigurationSource;
    }
}

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] paths = {"/auth/**", "/env"};
        
        //http.cors().configurationSource(CustomCorsFilter.configurationSource()); // Option 1

        http
            .csrf().disable()
            .exceptionHandling()
            .authenticationEntryPoint(this.authenticationEntryPoint)
        .and()
            .authorizeRequests()
            .antMatchers(paths)
            .permitAll()
        .and()
            .authorizeRequests()
            .antMatchers("/**")
            .authenticated()
        .and()
            .addFilterBefore(new CustomCorsFilter(), UsernamePasswordAuthenticationFilter.class); //option 2
}

这篇关于如何允许所有域的CrossOrigin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆