Spring Security @CrossOrigin SpringBoot中的正则表达式

holgip5t  于 2023-08-05  发布在  Spring
关注(0)|答案(3)|浏览(164)

我正在尝试定义origins,允许其执行REST服务。我正在使用Java(1.8),SpringBoot(1.5.9)。我试着以两种方式实现CORS:

@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value="/questions")
public String readCSV() throws IOException, URISyntaxException  {
    /** Some Logic **/
    return str;
}

字符串

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {    
    String origins = "http://localhost:8080";       
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "PUT", "POST")
                .allowedOrigins(origins)
                .maxAge(3600);
        super.addCorsMappings(registry);
    }
}


上述两种情况都有效。但是我想把http://localhost:8080改为一些有意义的正则表达式,它将匹配一些特定的域名,但是子域名和端口号可能会有所不同。
例如,我们假设 * 想要的域名 * 是innovation.com,少数 * 接受的URL * 是we.innovation.com:8081my.innovation.com:8090
问题是,每当我把一些正则表达式而不是静态URL,它抛出CORS错误,不允许访问服务。即使在我使用regex允许任何有效url的情况下,它也会阻止localhost:8080
我尝试了regex,如下所示:
^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+innovation.com(:\d{2,4})
^https?://(?:[^./@]+\.)*domain\.com(?![^/])
^(http[s]:\/\/)?([A-Za-z0-9-]{1,63}\\.)+innovation.com(:\d{2,4})

wlp8pajw

wlp8pajw1#

一个解决方案是扩展spring cors配置,有一个名为checkOrigin的方法,可以重写它来处理正则表达式:https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/web/cors/CorsConfiguration.java#L425-L455
幸运的是,已经有人这样做了:https://github.com/looorent/spring-security-jwt/blob/master/src/main/java/be/looorent/security/jwt/RegexCorsConfiguration.java

jq6vz3qz

jq6vz3qz2#

从Sping Boot 2.4.x或Spring 5.3开始,CorsRegistration可以将origin添加为模式。参见CorsRegistration#allowedOriginPatterns

yshpjwxd

yshpjwxd3#

使用config.setAllowedPatterns(List.of("http://*.localhost:4200"));可以做到这一点,请参阅差异,它是setAllowedPatterns而不是setAllowedOrigins
示例代码:

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://yourowndomain.com"));
        configuration.setAllowedOriginPatterns(Arrays.asList("https://*.otherdomain.com"));
        configuration.setAllowedMethods(
                Arrays.asList(HttpMethod.GET.toString(), HttpMethod.POST.toString(), HttpMethod.DELETE.toString()));
        configuration.setMaxAge(Duration.ofMillis(3600));
        configuration.setAllowedHeaders(
                Arrays.asList(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

字符串

相关问题