如何使用Angular 2发送OAuth2的客户端ID和密码ID?

时间:2017-01-23 14:41:56

标签: angular spring-security spring-security-oauth2

我使用资源服务器和授权服务器的spring boot开发了OAuth2的Rest API。我可以使用cURL,POSTMAN Rest客户端成功获取令牌,并可以使用OAuth提供的令牌请求授予的服务。现在,我需要知道如何使用angular2传递OAuth2 client_id,secret_id。 我正在通过请求  getOAuthToken(clientCredintial):Observable {

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;

}     但我在浏览器上获得例外     选项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 Uncaught Response {_body:ProgressEvent,status:0,ok:false,statusText:“”,headers:Headers ...} enter code here

2 个答案:

答案 0 :(得分: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());
    }

}

答案 1 :(得分:0)

使用纯javascript in this post解决了这个问题。对于角度5,我能够使用以下代码获得200响应状态:

getAccessToken(username: string, password: string): Observable<AuthToken> {

   let oauth2_token_endpoint = '<your_token_endpoint>';
   let oauth2_client_id = '<your_client_id>';
   let oauth2_client_secret = '<your_client_secret>';

    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded',
            // 'Authorization': 'Basic ' + btoa(oauth2_client_id + ':' + oauth2_client_secret)
        })
    };


    const body = 'client_id={0}&client_secret={1}&grant_type=password&username={2}&password={3}'
        .replace('{0}', oauth2_client_id)
        .replace('{1}', oauth2_client_secret)
        .replace('{2}', username)
        .replace('{3}', password);

    // console.log(body);

    return this.http.post<AuthToken>(oauth2_token_endpoint, body, httpOptions);
}

AuthToken界面:

export interface AuthToken {
    access_token: string,
    token_type: string,
    expires_in: number,
    refresh_token: string,
    scope: Array<string>
}

您的登录功能如下所示:

login(username: any, password: any): void {

    this.getAccessToken(username, password).subscribe(
        response => {
            // ...any login logic- cookies and all the good stuff goes here
            this.isLoggedIn = true; 
            console.log(response);
        },
        error => {
            this.isLoggedIn = false;
            console.log(error);
        });
}