Angular 2 Calling APIs

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements
  • Angular 2.0.1
Show requirements

A common need for any client-side application is to access resources from a data API. Some of these data resources will likely need to be protected such that only the user who is authenticated in the client-side app can access them. This can be achieved by protecting your API's endpoints with your Auth0 secret key and sending the user's JWT as an Authorization header when calling the API. For more detail on how to secure your API, see the server API documentation.

Sending Authenticated HTTP Requests

To make an authenticated request, angular2-jwt provides the AuthHttp helper which has the same interface as the Http module but automatically adds the authorization header to requests.

First, add AUTH_PROVIDERS from angular2-jwt:

// app/app.module.ts

import { AUTH_PROVIDERS } from 'angular2-jwt';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  providers: [
    // ...
    AUTH_PROVIDERS,
    // ...
  ],
  imports: [
    // ...
  ],
  bootstrap: [AppComponent]
})

Then import AuthHttp, inject it into your component, and use it to make the authenticated requests.

// app/ping.component.ts

import {Component} from '@angular/core';
import {Auth} from './auth.service';
import {AuthHttp} from 'angular2-jwt';
import 'rxjs/add/operator/map';

@Component({
  selector: 'ping',
  templateUrl: 'app/ping.template.html'
})
export class Ping {

  API_URL: string = 'http://localhost:3001';
  message: string;

  constructor(private auth: Auth, private authHttp: AuthHttp) {}

  public securedPing() {
    this.authHttp.get(`${this.API_URL}/secured/ping`)
      .map(res => res.json())
      .subscribe(
        data => this.message= data.text,
        error => this.message = error._body || error
      );
  }
}

Your request will have the Authorization header added automatically.

Authorization: Bearer eyJ0eXAiOiJKV1Qi...

By default, AuthHttp will fetch the token from localStorage using the id_token key. You can change the key used. Or you can create another function to get the token and set the provider manually. For more detail on available options, see: Configuration Options.

Not sending the JWT for Specific Requests

If you do not want to send the access token in the authorization header, you can use the default Angular Http client:

// app/ping.component.ts

import {Component} from '@angular/core';
import {Auth} from './auth.service';
import {AuthHttp} from 'angular2-jwt';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'ping',
  templateUrl: 'app/ping.template.html'
})
export class Ping {
  API_URL: string = 'http://localhost:3001';
  message: string;

  constructor(private auth: Auth, private http: Http, private authHttp: AuthHttp) {}

  // Makes a get to the api without authorization headers
  public ping() {
    this.http.get(`${this.API_URL}/ping`)
      .map(res => res.json())
      .subscribe(
        data => this.message = data.text,
        error => this.message = error._body
      );
  }
}
Use Auth0 for FREECreate free Account