解决SpringSecurity权限拦截造成的CORS跨域问题

关于什么是跨域,可以看一下阮一峰的 跨域资源共享 CORS 详解进入正题一般我们在开发前后端分离项目时,需要进行跨域配置,但是如果我们集成了SpringSecurity做安全校验,只配置跨域是不行的,还需要配置一下SpringSecurity使其支持CORS。@Overrideprotected void configure(HttpSecurity http) throws Exception { http // by default uses a Bean by the
摘要由CSDN通过智能技术生成

什么是跨域

判断是否跨域可通过以下三点:

三点有其一不满足就会造成跨域。

  • 协议相同
  • 域名相同
  • 端口相同

具体关于什么是跨域,可以看一下阮一峰的 跨域资源共享 CORS 详解


解决CORS跨域问题

  • 首先配置全局跨域

一般前后端项目后端都会配置,也可以使用Nginx配置,vue可以通过配置proxy

/**
 * 重写全局web配置
 *
 * @author Knox
 * @date 2020/12/6
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
   

    
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要使用Spring Security解决CORS跨域问题,可以按照以下步骤进行配置: 1. 添加CORS配置类:创建一个类,继承自`WebSecurityConfigurerAdapter`,并重写`configure(HttpSecurity http)`方法。 ```java @Configuration public class CorsConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOrigin("*"); // 允许所有来源 configuration.addAllowedMethod("*"); // 允许所有请求方法 configuration.addAllowedHeader("*"); // 允许所有请求头 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } } ``` 2. 启用CORS配置:在Spring Boot应用的入口类上添加`@EnableWebSecurity`注解。 ```java @EnableWebSecurity public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 通过以上配置,Spring Security会自动处理跨域请求,并允许所有来源、所有请求方法和所有请求头。你可以根据需要调整配置,例如指定允许的来源、方法和头部信息。 请注意,如果你的应用程序中使用了其他Spring Security配置,你需要将CORS配置类的优先级调整到较低的位置,以确保CORS配置被正确应用。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值