Spring Boot + Spring Security前后分离跨域问题

前端请求报错情况:

java.lang.IllegalArgumentException: When allowCredentials is true, 
allowedOrigins cannot contain the special value "*" since that cannot be set on the 

"Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them expli
//前端请求发生跨域错误,加入@CrossOrigin(origins = "*",maxAge = 3600)注解
@CrossOrigin(origins = "*",maxAge = 3600)

正常Spring Boot项目的跨域问题在Controller中加入@CrossOrigin(origins = "*",maxAge = 3600)注解即可,origins = "*"允许所有域名,maxAge = 3600是最大响应时间。

如果Spring Boot项目中整合了Spring Security就需要再做一个配置类WebMvcConfig

/*
Security跨域问题配置文件
*/

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");//允许任何域名
        corsConfiguration.addAllowedHeader("*");//允许任何头
        corsConfiguration.addAllowedMethod("*");//允许任何方法
        corsConfiguration.addExposedHeader("Authorization");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }


}

还需要将WebSecurityConfig中的configure方法中的http.csrf().disable();改成http.cors().and().csrf().disable();

        @Override
        protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 如果有允许匿名的url,填在下面
//                .antMatchers().permitAll()
                .anyRequest().authenticated()
                .and()
                // 设置登陆页
                .formLogin().loginPage("/login")
                // 设置登陆成功页
                .defaultSuccessUrl("/")
                //登录失败页
                .failureUrl("/login/error")
                .permitAll()
                // 自定义登陆用户名和密码参数,默认为username和password
//                .usernameParameter("username")
//                .passwordParameter("password")
                .and()
                .logout().permitAll();
                // CSRF跨域
                http.cors().and().csrf().disable();
    }

整体项目目录如下:

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值