首页 > 解决方案 > Facebook 登录引发对 XMLHttpRequest 的访问已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头

问题描述

我有 facebook 登录网络应用程序。我尝试单击前端的按钮,将我重定向到http://localhost:8080/login/facebook。端口 8080 在 Spring Boot 中是服务器端的。我对 facebook 登录有非常简单的配置,当我在纯 html 文件中使用具有属性的按钮时,一切正常:href="/login"。现在,当我在 React JS 中创建前端时,出现以下错误:

Access to XMLHttpRequest at 'https://www.facebook.com/dialog/oauth? client_id=455695445269575&redirect_uri=http://localhost:8080/login&response_type=code&scope=email&state=s4mR6Q' (redirected from 'http://localhost:8080/login/facebook') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:166 GET https://www.facebook.com/dialog/oauth?client_id=455695445269575&redirect_uri=http://localhost:8080/login&response_type=code&scope=email&state=s4mR6Q net::ERR_FAILED
dispatchXhrRequest @ xhr.js:166
handleSubmit @ LogIn.js:30

createError.js:17 Uncaught (in promise) Error: Network Error
at createError (createError.js:17)
at XMLHttpRequest.handleError (xhr.js:80)

我的Java配置如下:

@Configuration
@EnableOAuth2Sso
@Order(0)
public class SocialConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors().and()
            .cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues()).and()
            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/", "/login**", "/webjars/**", "/error**")
            .permitAll()
            .anyRequest()
            .authenticated()

            .and()
            .logout()
            .logoutSuccessUrl("/")
            .invalidateHttpSession(true)
            .deleteCookies("JSESSIONID")
            .permitAll()
            .and()
//                .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()
//                .and()
            .oauth2Login()
            .successHandler(myAuthenticationSuccessHandler())
            .and().csrf().disable();
}

@Bean
public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
    return new SimpleUrlAuthenticationSuccessHandler();
}

@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
    return new InMemoryClientRegistrationRepository(this.facebookClientRegistration());
}

private ClientRegistration facebookClientRegistration() {
    return CommonOAuth2Provider.FACEBOOK.getBuilder("facebook")
            .clientId("455695445269575")
            .clientSecret("efb40bb542ba92ded72c897e5d71a776").scope("public_profile", "email", "user_likes", "user_link", "user_location", "user_posts")
            .build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("*"));
    configuration.setAllowedHeaders(Arrays.asList("*"));
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
}

以及前端 React JS 中的按钮代码:

class LogIn extends React.Component {
constructor() {
    super();

    this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit() {
    $.ajaxSetup({
        beforeSend : function(xhr, settings) {
            if (settings.type == 'POST' || settings.type == 'PUT'
                || settings.type == 'DELETE') {
                if (!(/^http:.*/.test(settings.url) || /^https:.*/
                    .test(settings.url))) {
                    // Only send the token to relative URLs i.e. locally.
                    xhr.setRequestHeader("X-XSRF-TOKEN",
                        Cookies.get('XSRF-TOKEN'));
                }
            }
        }
    });
    axios.post("http://localhost:8080/login/facebook")
    .then(response => {
        console.log(response);
    })
}

方法 ajaxSetup 和这个非常简单的 facebook 登录示例来自教程:https ://spring.io/guides/tutorials/spring-boot-oauth2/

任何人都可以帮助我吗?

我在 stackoverflow.com 上尝试了一些关于 cors 的示例,但没有任何效果。

标签: reactjsspring-bootfacebook-login

解决方案


推荐阅读