Spring Boot + Spring Security + CORS 中没有“Access-Control-Allow-Origin”

2024-04-04

我正在尝试使用 Spring security 进行 CORS。这是我的 WebSecurityConfigurerAdapter :


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login();
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("*"));
        configuration.setAllowedMethods(List.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

这是我的 WebMvcConfigurer :

@EnableWebSecurity
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

但它给了我from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当前代码:安全配置.java

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .disable()//some stackoverflow solution(not accepted) said so
                .csrf()
                .disable()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login();
    }
}

WebConfig.java:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebSecurity
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH")
                .allowedHeaders("*")
                .allowCredentials(true);
    }

}

我什至尝试了一个过滤器(因为它在启动时崩溃,所以我将其删除) MyCorsFilter.java

@Configuration
public class MyCorsFilter {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedHeader("*");//tried list and all other collection stuff
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);//tried with negative value
        return bean;
    }
}

也尝试过

http
.headers()
.addHeaderWriter(
      new StaticHeadersWriter(
            "Access-Control-Allow-Origin",
            "http://localhost:3000"))

这是OAuth2配置 :

@Configuration
public class OAuth2Config {
    @Bean
    @RequestScope
    public GoogleOAuth2 google(OAuth2AuthorizedClientService clientService) {
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        String accessToken = null;
        if (authentication.getClass()
                .isAssignableFrom(OAuth2AuthenticationToken.class)) {
            OAuth2AuthenticationToken oauthToken =
                    (OAuth2AuthenticationToken) authentication;
            String clientRegistrationId =
                    oauthToken.getAuthorizedClientRegistrationId();
            if (clientRegistrationId.equals("google")) {
                OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
                        clientRegistrationId, oauthToken.getName());
                accessToken = client.getAccessToken().getTokenValue();
            }
        }
        return new GoogleOAuth2(accessToken);
    }

}

最近,当我尝试集成我的角度应用程序以使用 spring security 启用基于 JWT 的身份验证时,我遇到了完全相同的错误。

我看到您的安全配置中缺少什么。也许这就是问题所在。

首先,如果您在安全配置中配置了与 CORS 相关的所有内容,则无需创建过滤器或扩展 WebMvcConfigurer。

以下是您的安全配置中缺少的内容。

http.csrf().disable().cors().configurationSource(corsConfigurationSource())

这是我从昨天修复的工作代码中复制并粘贴的完整代码。

@Override
protected void configure(HttpSecurity http) throws Exception {

    http  
            .cors()
            .configurationSource(corsConfigurationSource())
            .and()
            .csrf()
            .disable()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .oauth2Login();

}

然后cors配置代码与你的几乎相同。

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    //the below three lines will add the relevant CORS response headers
    configuration.addAllowedOrigin("*");
    configuration.addAllowedHeader("*");
    configuration.addAllowedMethod("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

删除你的MyCorsFilter and WebConfig班级。两者都不需要。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Boot + Spring Security + CORS 中没有“Access-Control-Allow-Origin” 的相关文章

随机推荐

  • Xcode 4.5 无法在模拟器或设备上运行/加载应用程序

    我在 2007 年中的 Mac Mini 上运行 OS X Lion 10 7 5 上的 Xcode 4 5 我之前遇到过这个问题 当我构建时 模拟器和实际设备都不会运行应用程序 我正在使用 Phonegap 2 1 HTML JS Jqu
  • Recharts CompedChart 从零开始 X 轴刻度

    我正在使用 ComdedChart 和 shoing 条形图和线条 通常该线应从 x 轴的 0 处开始 但是当使用组合图表时无法做到这一点 如果您在上图中观察到勾选a应该从 x 轴开始 x 轴和 y 轴开始的 0 点 但事实并非如此 这是我
  • Matlab - 多维数据的PCA分析与重构

    我有一个大型多维数据集 132 维 我是数据挖掘的初学者 我想使用 Matlab 来应用主成分分析 不过 我看到网上有很多功能解释 但我不明白它们应该如何应用 基本上 我想应用 PCA 并从我的数据中获取特征向量及其相应的特征值 在此步骤之
  • 使用 XIB 实例化视图

    我有一个按照以下指南创建的 xib 如何创建自定义 iOS 视图类并实例化它的多个副本 在 IB 中 https stackoverflow com questions 9251202 how do i create a custom io
  • 如何在R中处理hdf5文件?

    我有一个文件在hdf5格式 我知道它应该是一个矩阵 但我想在其中读取该矩阵R这样我就可以研究它 我看到有一个h5r包应该有助于解决这个问题 但我没有看到任何简单易读 理解的教程 网上有这样的教程吗 具体来说 你如何阅读hdf5这个包的对象
  • 使用 REST API 更新 JIRA 票证状态

    我可以使用 CURL 命令并方便地使用 json 数据在 JIRA 中创建票证 curl D u X POST data H Content Type application json http rest api 2 issue 我现在尝试
  • 为什么 pack 和 grid 会覆盖父窗口小部件的预定义尺寸?

    我注意到每次创建 Tkinter 小部件并在小部件实例化期间或通过设置其尺寸时配置 http effbot org tkinterbook tkinter widget configuration htm稍后添加 一旦我添加 最后这些就不会
  • 这里使用持久ID来解决什么pickle问题?

    From https docs python org 3 library pickle html persistence of external objects https docs python org 3 library pickle
  • 如何定义分层数据结构的DDD聚合根?

    我目前正在尝试将领域驱动设计原则应用于我的开发实践 我一直致力于如何为按层次结构组织的数据定义聚合根 我们以文件夹结构为例 每个文件夹可以有 0 N 个子文件夹 子文件夹 0 N 也可以有 0 N 个子文件夹 依此类推 我对文件夹及其所有直
  • 将标签分配给相应的网格单元

    我从头开始编写了一个 YOLO 模型 并有一个 numpy 数组 如下所示 1 0 1 0 4 0 3 0 2 0 1 1 1 0 0 2 0 3 0 4 0 5 0 0 0 0 0 0 0 这就是它在 pandas 对象中的样子 Obj
  • 导入错误:无法导入名称“语言”

    我正在尝试运行 python 脚本 但收到此错误 from iso639 import languages ImportError cannot import name languages 我已经安装了iso639 但仍然出现此错误 任何想
  • 如何在 PHP 中从 ipinfo.io 获取位置?

    我在用ipinfo io http ipinfo io使用 PHP 获取我当前的城市 位置 但是 使用这段代码时我无法看到我的城市 ipaddress SERVER REMOTE ADDR function ip details ip js
  • Rails:如何限制 has_many 关联中的项目数量(来自父级)

    我想限制协会中的项目数量 我想确保用户拥有的东西不超过 X 件 这个问题之前被问过 https stackoverflow com questions 7863618 rails 3 1 limit user created objects
  • flutter 使用 url_launcher uri 发送电子邮件

    我正在使用 url launcher 在我的应用程序中使用系统电子邮件发送电子邮件 我正在使用下面的代码 这个人做得很好 void launchEmailSubmission async final Uri params Uri schem
  • 类只有静态字段和方法是不好的做法吗?

    我有一堂课 其中包括only静态成员变量和静态方法 本质上 它充当通用实用程序类 类只包含静态成员变量和静态方法是不好的做法吗 不 我一点也不这么认为 拥有一个充满实例方法的类是更糟糕的做法 而这些实例方法实际上并不依赖于特定实例 使它们静
  • int b=0,a=1;b=++a+++a; b 的值是多少?它的计算方法是什么? [复制]

    这个问题在这里已经有答案了 int main int b 0 a 1 initialize a and b b a a calculate assign the value of b print f d b return 0 b 的值是多少
  • CMake不知道Qt4 qmake在哪里

    我正在使用 Debian 操作系统 我试图指出 cmake 我的 Qt4 在哪里 我尝试构建 qjson 库及其 CMakeLists txt http pastebin com fKNp0Qgy http pastebin com fKN
  • 如何使用 os.listdir 仅选择一种文件类型?

    连接同一图像的 10 个条带后 我想将它们转换为反射率 然后将它们除以 10 000 尽管如此 我的文件夹中有两种类型的文件 但我只想将代码应用于 my img 文件而不是 hdr 您知道我如何使用 os listdir 进行此选择吗 我的
  • Jenkins 多配置项目处理并发设备使用

    Case 我有一个詹金斯奴隶女巫在移动设备 android ios 上运行葫芦测试 为了区分测试在哪些机器 iOS 的 mac 或 Android 的 Linux 上运行 我还使用Throttle 并发构建插件 通过这种方式 我可以区分设备
  • Spring Boot + Spring Security + CORS 中没有“Access-Control-Allow-Origin”

    我正在尝试使用 Spring security 进行 CORS 这是我的 WebSecurityConfigurerAdapter Configuration public class SecurityConfig extends WebS