我創建使用例如Spring Security中的OAuth2服務器從https://github.com/royclarkson/spring-rest-service-oauth採用了棱角分明2彈簧安全的oauth2 REST
在curl命令的OAuth2用戶認證請求如下如何提出請求。我想要Angular2中的等效語法。
curl -X POST -vu clientapp:123456 http://localhost:8080/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"
這裏是我的嘗試:
import { Injectable } from '@angular/core';
import {Http, Headers, RequestOptions, RequestMethod} from '@angular/http';
import {Router} from '@angular/router';
@Injectable()
export class AuthService {
isAuthenticated: boolean = false;
userId;
constructor(private http: Http, private router: Router) { }
login(usercreds){
let client_id = 'clientapp';
let client_secret = '123456';
var basicheader = btoa(client_id + ':' + client_secret);
console.log(basicheader);
var headers = new Headers();
headers.append('Authorization', 'Basic' + basicheader);
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
//let options = new RequestOptions({method: RequestMethod.Post, headers: headers });
var creds = 'username=' + usercreds.username + '&password=' + usercreds.password+'credentials=true&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp';
console.log(creds);
return new Promise((resolve) => {
this.http.post('http://localhost:8080/oauth/token', JSON.stringify(creds), {headers:headers}).subscribe((data) => {
if(data.json().success) {
this.userId = data.json().userId;
this.isAuthenticated = true;
}
resolve(this.isAuthenticated);
})
})
}
}
但是,當我啓動這個應用程序的谷歌Chrome瀏覽器開發者模式,返回此錯誤:
- 的XMLHttpRequest無法加載http://localhost:8080/oauth/token。預檢響應具有無效的HTTP狀態碼401
- 例外:URL 0:與狀態響應空