No 'Access-Control-Allow-Origin' when acce

2019-08-13 01:35发布

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 code:

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

I am following this tutorial:https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_click

Gmail login button

enter image description here

Gmail API setup

enter image description here

Application.properities:

enter image description here

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

enter image description here

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

1条回答
我命由我不由天
2楼-- · 2019-08-13 01:40

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

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

Goodluck!

查看更多
登录 后发表回答