2017-01-23 82 views
1

我有使用資源服務器和授權服務器使用spring啓動開發的OAuth2的其他API。我可以使用cURL,POSTMAN Rest客戶端成功獲取令牌,並可以使用OAuth提供的令牌請求授予的服務。現在,我需要知道如何使用angular2傳遞OAuth2 client_id,secret_id。 我傳遞請求作爲 getOAuthToken(clientCredintial):可觀察{如何使用Angular 2發送OAuth2的客戶端ID和祕密ID?

var body = `username=admin&password=nex1234`; 
var headers = new Headers(); 
headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
let response = this.http.post(`${AppSettings.BACK_ENDPOINT}/oauth/token`,body,{ headers: headers }); 
let oauthTokenItems = response.map(mapOAuthTokenItems); 
return oauthTokenItems; 

} 但我收到的瀏覽器的例外如 OPTIONS http://localhost:8080/rwsweb/oauth/token 401()

oauth-token:1 XMLHttpRequest cannot load     http://localhost:8080/rwcweb/oauth/token. Response for preflight has invalid  HTTP status code 401 
error_handler.js:47 EXCEPTION: Response with status: 0 for URL: null 
ErrorHandler.handleError @ error_handler.js:47 
next @ application_ref.js:272 
schedulerFn @ async.js:82 

Subscriber.js:227未捕獲的響應{_body:ProgressEvent,狀態:0,ok:false,statusText:「」,標題:Headers ...} enter code here

回答

0

使用代碼:

import { Injectable } from '@angular/core' 
import { Http } from '@angular/http'; 
import { Headers, RequestOptions } from '@angular/http'; 

@Injectable() 
export class LoginService { 
    private urlLogin: string; 

    constructor(private http: Http) { 
     this.urlLogin = "http://yourserver/oauth/token"; 
    } 

    public login(user) { 

     let headers = new Headers({ 
      "Content-Type": "application/x-www-form-urlencoded", 
      "Accept": "application/json", 
      "Authorization": "Basic " + btoa("yourclientid" + ':' + "yourclientsecret") 
     }); 

     let options = new RequestOptions({ headers: headers }); 

     let data = "username=" + user.yourlogin + "&password=" + encodeURIComponent(user.yourpass) + "&grant_type=password&" + 
      "client_secret=yourclientsecret&client_id=yourclientid"; 

     return this.http.post(this.urlLogin, data, options) 
      .map(res => res.json()); 
    } 

} 
+0

我上面試過,但現在我在Chrome brawser得到一個例外,因爲XMLHttpRequest的不能加載的http://本地主機:8080/rwcweb /的OAuth /令牌。預檢的響應具有無效的HTTP狀態代碼401 –

+0

驗證憑證是否相關。您的用戶,通過,grant_type ... –

+0

您在郵​​遞員的測試? –

相關問題