【发布时间】:2017-09-27 08:29:48
【问题描述】:
我正在尝试创建一个前端和后端资产分开的应用程序。举例来说,假设前端最终将托管在 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 端,而您无法更改。您可能希望从后端代码发出 github oauth 请求,而不是像现在这样。
标签: java spring authentication oauth-2.0 cors