没有“访问控制允许来源”,当访问Gmail的API(No 'Access-Control-A

2019-09-30 02:45发布

我使用的春天的oauth2和角度进行测试。 春天启动的应用程序是在端口8081和角度是4200,我的春天已经设置CORS端口4200。 当我点击Gmail按钮,春风不给任何异常,只有对铬,我得到了没有“访问控制允许来源”错误。

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。 我已经添加本地主机:8081到Gmail API,但我仍然得到以下错误

感谢您的帮助,我便无法弄清楚什么是错我的应用程序。

Answer 1:

几天以前有同样的错误,我的问题是,我是不提供与内容类型一起API密钥

所以我所做的就是创建了一个包含了新的HTTPHeader然后我把它添加到我的API调用这样一个对象调用httpOptions:

import { HttpClient, HttpHeaders } from "@angular/common/http";

  constructor(private httpClient: HttpClient) {}

      httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      Authorization: "API_KEY"
    })
  };

  createNewSubscriber() {
    this.httpClient
  .post(
    "https://endpoint",
    {
      name: this.data.form.manager.managerFirstName,
      last_name: this.data.form.manager.managerLastName,
      email: this.data.form.manager.managerEmail,
      external_id: this.data.managerUUID,
      group_id: `${this.data.form.companyName}${this.data.form.teamName}`
    },
    this.httpOptions
  )
  .subscribe(
    data => {
      console.log("POST Request is successful ", data);
    },
    error => {
      console.log("Error", error);
    }
  );
};

这为我工作,希望它为你的作品太

祝好运!



文章来源: No 'Access-Control-Allow-Origin' when access gmail api