How to send the client id and secret id of OAuth2 using Angular 2?

岁酱吖の 提交于 2019-12-08 06:32:17

问题


I have the Rest API for OAuth2 developed using spring boot with resource server and authorization server. I could successfully fetch the token using cURL, POSTMAN Rest client and could request the granted service using the token provided by OAuth. Now, i need to know how to pass the OAuth2 client_id, secret_id using angular2. i am passing request as 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;

} but i am getting Exceptions on Browser as 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 Uncaught Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers…}enter code here


回答1:


Use the code:

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());
    }

}



回答2:


This problem was solved using pure javascript in this post. For angular 5, I was able to get a 200 response status using this code:

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 Interface :

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

Your Login function would look like this:

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);
        });
}


来源:https://stackoverflow.com/questions/41808929/how-to-send-the-client-id-and-secret-id-of-oauth2-using-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!