Home > Enterprise >  Consuming RESTful API with Angular Stack
Consuming RESTful API with Angular Stack

Time:12-13

I have an Angular 12 web application where I need to display data from a RESTful API protected by OAUTH 2.0 using a Client ID and an API key. What is the secure and standard way to implement this? Any advice, examples, or tutorials would be helpful.

CodePudding user response:

There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

Create a HTTP helper and add this code there,

    constructor(
    private http: HttpClient
  ) {}

.

postWithToken(url: string, params: object): Observable<any> {
  let headers = new HttpHeaders({
    "Content-Type": "application/json",
    "Access-Control-Allow-Methods": "*",
    "Access-Control-Allow-Origin": "*",
    Authorization: "Bearer AYjcyMzY3ZDhiNmJkNTY",
  });
  return this.http
    .post<any>("http://localhost/"  url, params, {
      headers: headers,
    })
    .pipe(
      tap(
        (data) => {
          return data;
        },
        (error) => {
          if (error.status == 500) {
            console.log("No valid Session Exists");
            return;
          } else {
            console.log("Internal server error!", 3000);
            return;
          }
        }
      )
    );}

Where

AYjcyMzY3ZDhiNmJkNTY

is your OAuth access token. This token can read from browser cookie or session.

You can call this from your service.js file

 httpService
  .postWithToken("YOUR API END-POINT", requestBody)
  .subscribe((data) => {
    if (
      data.httpStatusCode == 200 &&
      data.data != null &&
      data.data != undefined
        ) {
//your code here to display the data from BE server
}
  • Related