我正在尝试创建一个将前端和后端资产分开的应用程序。例如,假设前端最终将托管在 gh-pages 上,而后端将部署在 Heroku 上。
我想使用 OAuth2.0 协议对我的客户进行身份验证,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() 按钮时,我都会得到相同的结果:
我想问一下,这样的资产分割是否可行?如果是这样,我在哪里出错?
谢谢!
您看到的 CORS 消息是因为您的代码正在向其发送跨域请求,https://github.com/login/oauth/authorize
但来自 github 的Access-Control-Allow-Origin
响应不包含响应标头。
因此,您对 Spring 代码中的 CORS 配置所做的任何更改都无关紧要 — 不会有任何区别,因为需要更改的行为在 github 端,而您无法更改它。
您可能想要从后端而不是像您现在所做的前端代码执行 oauth 请求,或者使用https://github.com/Rob--W/cors-anywhere/设置 CORS 代理或这样,或者设置类似https://github.com/prose/gatekeeper 的东西:
由于一些与安全相关的限制,Github 阻止您在仅客户端应用程序上实现 OAuth Web 应用程序流。
这是一个真正的无赖。因此,我们构建了 Gatekeeper,这是您让它工作所需的缺失部分。
Gatekeeper 与 Github.js 配合得很好,它可以帮助您从浏览器访问 Github API。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句