Jaccs
Jaccs

Reputation: 1072

How to do oAuth2 Basic authentication with angular 2?

I'm doing oauth2 with angular 2.

Here is the POST URL = "http://localhost:8080/OAuth2Example/oauth/token?grant_type=password&username=bill&password=abc123".

how to pass clientId and client secret in frontend with one of validated user and get access token?

If any plugin is available in angular2 or any configuration please suggest me!

I tried like,

private getHeaders(){
    // I included these headers because otherwise FireFox
    // will request text/html
    let headers = new Headers();
    let auth_data = 'username=my-trusted-client&password=secret';
    headers.append('Accept', 'application/json');
    headers.append('Authorization', auth_data);
    return headers;
  }

  testRequest() {
     let data = 'grant_type=password&username=bill&password=abc123';
     let postResponse = this.http
      .post(`${this.baseUrl}/oauth/token?`, data, {headers: 
         this.getHeaders()})
       .toPromise()
      .then(this.mapResult);
     return postResponse;

}

When i execute Post call,

XMLHttpRequest cannot load http://localhost:8080/OAuth2Example/oauth/token?/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

this error I saw at console.

I have a postman collection snaps to quickly identify what i need exactly, I achieved oauth2 from postman like below.

enter image description here

enter image description here

This is exactly i need to get it from angular 2 too.

Thanks,

Upvotes: 1

Views: 2237

Answers (1)

k11k2
k11k2

Reputation: 2044

If any plugin is available in angular2 or any configuration please suggest me!

There are lot of examples for different platform as you asked for angular 2 you could follow this link which work for me LINK

and your exception looks like regarding cors.

Upvotes: 0

Related Questions