我正在使用spring oauth2和angular进行此测试。 Spring Boot应用程序在端口8081上,而Angular在4200上,我已经在Spring上为端口4200设置了CORS。当我单击Gmail按钮时,Spring没有任何例外,仅在chrome上,没有No'Access-Control-Allow-Origin'错误。
Java代码:
@Autowired
private OAuth2ClientContext oauthClientContext;
@Value("${cross-origin-url}")
private String crossOriginUrl;
@Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.cors()
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.antMatcher("/**").authorizeRequests()
.antMatchers("/login**","/","/test","/login/gmail").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.addFilterBefore(oauthGmailFilter(), BasicAuthenticationFilter.class)
;
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration cors = new CorsConfiguration();
cors.addAllowedOrigin(crossOriginUrl);
source.registerCorsConfiguration("/**", cors.applyPermitDefaultValues());
return source;
}
@Bean
public Filter oauthGmailFilter() {
OAuth2ClientAuthenticationProcessingFilter gmailFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/gmail");
OAuth2RestTemplate gmailTemplate = new OAuth2RestTemplate(gmail(),oauthClientContext);
gmailFilter.setRestTemplate(gmailTemplate);
UserInfoTokenServices tokenService = new UserInfoTokenServices(gmailResource().getUserInfoUri(),gmail().getClientId());
tokenService.setRestTemplate(gmailTemplate);
gmailFilter.setTokenServices(tokenService);
return gmailFilter;
}
@Bean
@ConfigurationProperties("gmail.client")
public AuthorizationCodeResourceDetails gmail() {
return new AuthorizationCodeResourceDetails();
}
@Bean
@ConfigurationProperties("gmail.resource")
public ResourceServerProperties gmailResource() {
return new ResourceServerProperties();
}
@Bean
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
我正在关注本教程:https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_click
Gmail login button
Gmail API setup
Application.properities:
代码与教程链接相同,我只是从facebook更改为gmail。我已经将localhost:8081添加到Gmail API,但是仍然出现以下错误
感谢您的帮助,我无法弄清楚应用程序出了什么问题。
答案 0 :(得分:0)
几天前发生了同样的错误, 我的问题是我没有提供API密钥以及内容类型
所以我创建了一个名为httpOptions的对象,其中包含一个新的httpHeader,然后将其添加到我的api调用中,如下所示:
tf.contrib.learn
这对我有用,希望对您也有用
祝你好运!