Vue + spring boot + spring security 跨域访问

本文主要介绍在项目中用到前端Vue 技术,后端spring boot  + spring security权限框架,在vue页面中使用Ajax请求后端数据,后台响应并返回结果。具体配置如下:

Vue前端技术

ajaxPost('地址','参数',res =>{})该块依个人写法不同,名称自己编写。前端Vue页面登录请求后台时,

参数传递用户名密码格式:'username=admin1&password=111111'

主要介绍后端配置情况,首先在SpringMVC的配置类中

class WebMvcConfig extends WebMvcConfigurerAdapter配置addCorsMappings方法,该方法是处理跨域请求
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("*","http://localhost:8001/")//Vue 项目的服务地址和端口号 可用*号代替
            .allowCredentials(true)
            .allowedMethods("GET", "POST", "DELETE", "PUT")
            .maxAge(3600);
}

然后在Security的配置类中 WebSecurityConfig extends WebSecurityConfigurerAdapter放过 option 请求,让Spring security 不校验preflight request 。

protected void configure(HttpSecurity http) throws Exception {
    //设置option
    http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll(); //放过 option 请求

}

到此配置完毕。

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值