Reactjs Facebook登录抛出对XMLHttpRequest的访问已被CORS策略阻止:No';访问控制允许原点';标题已存在
我有facebook登录web应用程序。我试着点击前端的按钮,将我重定向到。端口8080是Spring boot中的服务器端。我有一个非常简单的facebook登录配置,当我在普通html文件中有一个按钮,该按钮具有属性:href=“/login”时,一切都很好。现在,当我在React JS中创建前端时,我发现以下错误:Reactjs Facebook登录抛出对XMLHttpRequest的访问已被CORS策略阻止:No';访问控制允许原点';标题已存在,reactjs,spring-boot,facebook-login,Reactjs,Spring Boot,Facebook Login,我有facebook登录web应用程序。我试着点击前端的按钮,将我重定向到。端口8080是Spring boot中的服务器端。我有一个非常简单的facebook登录配置,当我在普通html文件中有一个按钮,该按钮具有属性:href=“/login”时,一切都很好。现在,当我在React JS中创建前端时,我发现以下错误: Access to XMLHttpRequest at 'https://www.facebook.com/dialog/oauth? client_id=4556954452
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登录的这个非常简单的示例来自教程:
有人能帮我吗
我在stackoverflow.com上尝试了一些关于cors的示例,但没有任何效果。在应用程序中添加以下代码
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() {
}
}
不工作,因为我不使用控制器。我在其中一个配置类中有注释@EnableAuth2Sso。我添加了这段代码,它与之前的错误相同。也许我在developers.facebook.com的配置有误?我只添加到网站的URL,没有我发现这篇文章在。它说不能从ajax请求中调用dialog facebook,但它指出angular和我有react js。你能看看这个帖子吗?我在handler submit window.location.href=“”中执行了此操作,但我收到了相同的错误,并下一次重定向到401响应