访问gmail API时没有"Access-Control-Allow-Origin" [英] No 'Access-Control-Allow-Origin' when access gmail api

查看:64
本文介绍了访问gmail API时没有"Access-Control-Allow-Origin"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spring oauth2和angular进行此测试. Spring Boot应用程序在端口8081上,而Angular在4200上,我已经在Spring上为端口4200设置了CORS.当我单击Gmail按钮时,Spring没有任何例外,仅在chrome上,没有No'Access-Control-Allow-Origin'错误.

I am using spring oauth2 and angular for this test. Spring boot app is on port 8081 and Angular is on 4200, I've setup CORS for port 4200 on Spring. When I click on Gmail button, Spring isn't give any exception, only on chrome, I got the No 'Access-Control-Allow-Origin' Error.

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/指南/教程/spring-boot-oauth2/#_ social_login_click

Gmail login button

Gmail API setup

Application.properities:

代码与教程链接相同,我只是从facebook更改为gmail.我已经将localhost:8081添加到Gmail API,但是仍然出现以下错误

Code is the same from the tutorial link, I just change from facebook to gmail. I've already added localhost:8081 to Gmail API, but I am still getting the following error

感谢您的帮助,我无法弄清楚我的应用程序出了什么问题.

Thanks for the help, I could't figure out what is wrong with my app.

推荐答案

几天前发生了相同的错误, 我的问题是我没有提供API密钥以及内容类型

Had the same error a couple of days ago, my problem was that I wasn't providing the API key along with the content type

因此我创建了一个名为httpOptions的对象,其中包含一个新的httpHeader,然后将其添加到我的api调用中,如下所示:

so what I did was created an object called httpOptions containing a new httpHeader then I added it to my api call like this:

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

这对我有用,希望它对您也有用

This worked for me, hope it works for you too

祝你好运!

这篇关于访问gmail API时没有"Access-Control-Allow-Origin"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆