OAuth2.0 - authentication using GitHub with front-

2020-02-11 12:28发布

I'm trying to create an application that has front-end and back-end assets separated. For the sake of example, let's say that front-end side will eventually be hosted on gh-pages, while back-end is gonna be deployed on Heroku.

I want to use OAuth2.0 protocol for authenticating my clients with GitHub being my main provider.

As a 'Prove of Concept', I wanted to create some dummy app that takes advantage of this kind of authentication. Below is the code:

Front-end (Angular2 application) - launched on localhost:8080

// template
<h1>
  {{title}}
</h1>
<button type="button" (click)="getServerResponse()">getServerResponse()</button>
<h1>{{response}}</h1>

// component
export class AppComponent {
  title = 'app works!';
  response = 'server response';

  constructor(private http: Http) {}

  getServerResponse() {
    this.http.get('http://localhost:9000/hello')
      .subscribe(res => this.response = JSON.stringify(res.json()));
  }
}

Back-end (Java + Spring application) - launched on localhost:9000

// Application.java
@SpringBootApplication
@EnableOAuth2Sso
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

// HelloController.java
@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        return "Hello!";
    }
}

// FilterConfig.java
@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(1);
        return bean;
    }

}

// resources/config/application.yml
security:
  oauth2:
    client:
      clientId: xxx
      clientSecret: yyy
      accessTokenUri: https://github.com/login/oauth/access_token
      userAuthorizationUri: https://github.com/login/oauth/authorize
      clientAuthenticationScheme: form
      scope: repo, user, read:org
    resource:
      userInfoUri: https://api.github.com/user
  filter-order: 5

server:
  port: 9000

I've tried registering both localhost:8080 and localhost:9000 as OAuth Application on GitHub, but regardless of that whenever I try to click on getServerResponse() button, I get the same result:

enter image description here

I wanted to ask whether it is even possible to have assets separated in such a manner? And if so, where do I make mistake?

Thank you!

2条回答
狗以群分
2楼-- · 2020-02-11 13:17

If you are using Spring-Boot you can do this in your spring configuration:

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080", "http://127.0.0.1:8080");
            }
        };
    }
查看更多
家丑人穷心不美
3楼-- · 2020-02-11 13:24

The CORS message you’re seeing is because your code is sending a cross-origin request to https://github.com/login/oauth/authorize but the response from github doesn’t include the Access-Control-Allow-Origin response header.

So whatever changes you make to the CORS configuration in your Spring code won’t matter—it won’t make any difference because the behavior that would need to change is on the github side and you can’t change that.

You probably either want to do the oauth request from your backend rather than your frontend code as you’re doing now, or else set up a CORS proxy using https://github.com/Rob--W/cors-anywhere/ or such, or else set up something like https://github.com/prose/gatekeeper:

Because of some security-related limitations, Github prevents you from implementing the OAuth Web Application Flow on a client-side only application.

This is a real bummer. So we built Gatekeeper, which is the missing piece you need in order to make it work.

Gatekeeper works well with Github.js, which helps you access the Github API from the browser.

查看更多
登录 后发表回答