前后端分离SpringSecurity跨域问题解决方案(亲测可用)

当我们进行不同的ip地址或者不同的协议请求数据的时候,就会报跨域错误。然后我们可以使用下面的解决方案解决跨域的问题。

后端

1.在SpringSecurity配置类中配置http.cors(),还有关闭跨域攻击http.csrf().disable()

/**
 * 自定义SpringSecurity配置类
 */
@Configuration
public class MySecurityConfigure extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 解决跨域问题
        http.cors();

        http.authorizeRequests()
                .mvcMatchers("/test").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .logout()
                .logoutUrl("/tuichu")
                .logoutSuccessHandler(new LogoutSuccessHandler())
                .and()
                .exceptionHandling().authenticationEntryPoint((request, response, ex) -> {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().println("请认证之后在操作");

        }).and().csrf().disable();
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }


}

然后创建config包,添加一个跨域配置

package cn.guan.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
}

前端

这个配置可以不配也可以解决跨域的问题

处理跨域:都配上

在vite配置文件中配置proxy

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), WindiCSS()],
  resolve: {
    alias: {
      "~": path.resolve(__dirname,'src')
    }
  },
  // 配置前端服务地址和端口
  server: {
    host: '0.0.0.0',
    port: 8991,
    // 是否开启 https
    https: false,
  },
  proxy: {// 跨域代理
    '/apis': {
      // target: 'http://' + env.VUE_APP_BASE_API,
      target: 'http://localhost:8080', // 
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/apis/, '')
    },
    // 代理 WebSocket 或 socket
    // '/socket.io': {
    //   target: 'ws://localhost:3000',
    //   ws: true
    //  }
  }
})

然后axios配置使用代理

// 1.引入axios实例
import axios from "axios";



// 2.构件一个axios实例
const service = axios.create({
  baseURL: '/apis'
})


// 3.导出请求实例
export default service

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bboy_guan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值