简体   繁体   中英

Facebook Login throws an Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present

I have facebook login web app. I try click on the button in frontend which redirect me to http://localhost:8080/login/facebook . Port 8080 is server-side in Spring boot. I have very simple configuration for facebook login and earlier everything works fine when I had button in plain html file with button which have attribute: href="/login". Now when I created frontend in React JS I get this errors:

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)

My configuration from Java below:

@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;
}
}

And the code for button in frontend 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);
    })
}

Method ajaxSetup and this very simple example for facebook login come from tutorial: https://spring.io/guides/tutorials/spring-boot-oauth2/

Anyone can help me ?

I was trying with a few exampple at stackoverflow.com about cors and nothing works.

Add this below code in your application

import javax.inject.Named;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

    @Named
    public class SimpleCORSFilter implements Filter {

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, accept, content-type");
            chain.doFilter(req, res);
        }

        public void init(FilterConfig filterConfig) {
        }

        public void destroy() {
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the request socket io react Access to XMLHttpRequest has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource React component has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Cors enabled but Still got this "Origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present " ' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Getting 'fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present... on React page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM