因此,我已经使用Spring(java)编写了REST API,该API使用基本身份验证进行了安全保护,并且还负责处理社交登录。以下是Facebook登录的配置。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//autowired
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Bean
public ProviderSignInController providerSignInController() {
return new ProviderSignInController(connectionFactoryLocator(), usersConnectionRepository(),
new FacebookSignInAdapter());
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login*", "/signin/**", "/signup/**").permitAll()
.anyRequest().authenticated()
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable()
;
}
@Bean
public ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new FacebookConnectionFactory(environment.getProperty("facebook.clientId"),
environment.getProperty("facebook.clientSecret")));
return registry;
}
@Bean
public UsersConnectionRepository usersConnectionRepository() {
return new InMemoryUsersConnectionRepository(connectionFactoryLocator());
}
}
使用的依赖项:
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-facebook</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
现在,我的前端是使用React.js编写的,并且在https://localhost:3000
上运行。它具有一个按钮使用Facebook登录,该按钮向POST
发送一个https://localhost:8443/signin/facebook
请求。 /signin/facebook
是Spring-Security提供的URL。 REST API返回一个重定向URL,浏览器将阻止该重定向URL来解决CORS问题。我了解CORS,并在后端进行了配置(这就是前端能够发送请求的原因)。
Access to XMLHttpRequest at 'https://www.facebook.com/v2.5/dialog/oauth?client_id=2198xxxxxx91&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8443%2Fsignin%2Ffacebook&state=xxxx' (redirected from 'https://localhost:8443/signin/facebook') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
那么,解决方案是什么?我用谷歌搜索,并在某处看到CORS是由后端而不是前端处理的。但是后端已经在处理CORS。应该是什么配置?