SpringCloud+Security+CORS跨域问题

问题描述

        SpringCloud搭配Security出现跨域问题,有的报No Access-Control-Allow-Origin,有的报It does not have HTTP ok status,有的只在Gateway出现,有的只在调用子服务出现

问题分析

        根据报错分析,说明服务器对于请求响应没有跨域配置,参考spring-cloud的跨域配置又没啥问题,那只能是因为加入了security导致的了。

问题解决

        1、检查security有没有跨域配置,这里有几种方式,采用下面一种快速方便稳定,在security配置中加入

                .and()
                // 开启跨域配置
                .cors()
                .configurationSource(corsConfigurationSource())
CorsConfigurationSource corsConfigurationSource() {
        // 提供CorsConfiguration实例,并配置跨域信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

        2、加入上面方法以后,可能正常,对于正常权限的子服务跨域必是正常,那其他的是什么原因呢,原来security中如果配置了权限不足,和登录成功,登录失败的handler则会跨域失败,因为你走的是自己自定义的Handler,例如下面的配置

                // 登录成功handler
                .authenticationSuccessHandler(successHandler)
                // 登陆失败handler
                .authenticationFailureHandler(authenticationFailureHandler)
                // 无访问权限handler
                .authenticationEntryPoint(serverAuthenticationEntryPoint)
                .and()
                .logout()
                // 登出成功handler
                .logoutSuccessHandler(logoutSuccessHandler)

既然是这样那在各自的handler里要加上跨域响应,如下

response.getHeaders().set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,"*");
        response.getHeaders().set(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true");
        response.getHeaders().set(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS,"GET,POST,DELETE,PUT,OPTIONS");

response.getHeaders().set(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,"*");

至此,完美解决,希望对你有用的,小伙伴们~~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值