我正在尝试创建一个将前端和后端 Assets 分开的应用程序。举个例子,假设前端最终将托管在 gh-pages 上,而后端将部署在 Heroku 上。
我想使用 OAuth2.0 协议(protocol)来验证我的客户,并将 GitHub 作为我的主要提供商。
作为“概念证明”,我想创建一些利用这种身份验证的虚拟应用程序。下面是代码:
前端(Angular2 应用程序)- 在 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()));
}
}
后端(Java + Spring 应用程序)- 在 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
我尝试在 GitHub 上将 localhost:8080 和 localhost:9000 注册为 OAuth 应用程序,但无论何时我尝试单击 getServerResponse() 按钮,我得到相同的结果:
我想问这样的 Assets 分割是否可行?如果是这样,我在哪里犯了错误?
谢谢!
最佳答案
您看到的 CORS 消息是因为您的代码正在向 https://github.com/login/oauth/authorize
发送跨源请求,但 github 的响应并未发送包含 Access-Control-Allow-Origin
响应 header 。
因此,您对 Spring 代码中的 CORS 配置进行的任何更改都无关紧要 - 不会产生任何影响,因为需要更改的行为位于 github 端,而您无法更改它。
您可能想要从后端而不是像现在一样从前端代码执行 oauth 请求,或者使用 https://github.com/Rob--W/cors-anywhere/ 设置 CORS 代理或类似的,或者设置类似 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.
关于java - OAuth2.0 - 使用 GitHub 进行身份验证,前端和后端运行在不同的服务器上。 CORS错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43693447/