技术: 春天的靴子 角2 google oauth
spring boot code尝试连接到google auth进行登录。 angular code使http.get获取用户信息。我收到上面的403错误。早些时候,我在firefox中得到了“CORS预检频道没有成功”。转向chrome给了我403。
我搜索了SO和google。尝试了一些修复,但没有解决我的问题。任何帮助表示赞赏。
启动控制器
@CrossOrigin(origins = {"http://localhost:4200"})
@RestController
public class UserRestController {
@RequestMapping("/")
public RedirectView index()
{
RedirectView redirectView = new RedirectView();
redirectView.setUrl("http://localhost:4200/");
return redirectView;
// return "index";
}
@CrossOrigin(origins = {"http://localhost:4200"})
@RequestMapping("/user")
public Principal sayHello(Principal principal) {
return principal;
}
}
angular 2 code
import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
@Injectable()
export class AppComponent implements OnInit {
title = 'app works!';
user : any;
private headers:Headers = new Headers({'Content-Type': 'application/json'});
private auth64 = btoa("my-trusted-client:secret");
private tokenHeaders = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic '+this.auth64
});
constructor(private http : Http){
}
// method for getting user details
getUser() {
// this.http.get('http://localhost:8080/user').success(function(user) {
// this.user = user;
// console.log('Logged User : ', user);
// }).error(function(error) {
// // $scope.resource = error;
// });
let options = new RequestOptions({ headers: this.tokenHeaders});
// let options = { headers : this.tokenHeaders};
this.http.get('http://localhost:8080/user', options)
.subscribe ((data :Response)=> {
this.user = data;
console.log('Logged User : ', data);
});
}
// method for logout
logout() {
// this.http.post('http://localhost:8080/logout', null);
this.user = null;
}
ngOnInit() {
this.getUser();
}
}
答案 0 :(得分:0)
尝试使用:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
这是一个Chrome扩展程序,可以帮助您继续进行开发和测试。
生产:
我不太了解spring,但这是我在遇到同样问题时在PHP代码中所做的。
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 86400'); // for 1 day
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token ,
Authorization');`
希望它有所帮助!
答案 1 :(得分:0)
请检查此回答https://stackoverflow.com/a/46433046/836701 并且您希望使用用于身份验证的相同库来获取API中的用户信息。