关于前后端分离中CORS跨域问题

在前后端分离中,前端的域或端口与后端的域或端口不一致的情况下,浏览器默认会阻止前端请求后端,因此我们为了使前端请求能够得到服务器响应并返回数据,需要做一些设置。

基于springboot+vue

一.CORS服务器端设置

@Configuration
public class MyConfig implements WebMvcConfigurer {
    //静态资源URI和位置映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/")
                //设置静态资源缓存1年
                .setCachePeriod(3153600);
    }
    // CORS设置,任何请求,任何来源,任何方法,任何头,允许凭证
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true).maxAge(3600);
    }
}

另外,如果采用了springSecurity,则需要进一步进行安全设置,重点内容如下,需要安全级别中启用CORS

//使用Spring Security,请确保在Spring安全级别启用CORS
      .cors()

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    private MyUserDetalisService myUserDetalisService;

    public MySecurityConfig(MyUserDetalisService myUserDetalisService) {
        this.myUserDetalisService = myUserDetalisService;
    }

    //http安全配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()  //所有请求拦截
                .antMatchers("/static/**").permitAll() //放在所有拦截的前面放行不需要拦截的资源
                .antMatchers("/login").permitAll()  //放行登录
                .antMatchers("/logout").permitAll() //放行注销
                .antMatchers("/reg").hasAnyAuthority("REGUSER")//此页需要权限
                .anyRequest().authenticated() //除上所有拦截需要用户认证
                .and()
                .formLogin().loginProcessingUrl("/login")
                //登录成功后的返回结果
                .successHandler(new AuthenticationSuccessHandlerImpl())
                //登录失败后的返回结果
                .failureHandler(new AuthenticationFailureHandlerImpl())
                .and()
                .logout().logoutUrl("/logout")
                //登出后的返回结果
                .logoutSuccessHandler(new LogoutSuccessHandlerImpl())
                .and()
                //使用Spring Security,请确保在Spring安全级别启用CORS
                .cors().and()
                .csrf().disable(); //关闭csrf校验

    }
    //认证管理器配置
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetalisService)
                //查询时需要密码加密后和数据库做比较
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}

二、前端中

在axios配置中也需要启用凭证,否则axios请求会被后端安全拦截,转向/login请求

axios.defaults.withCredentials = true

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值