Angular 2+ Calling an API

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Angular 2+
Show requirements

Most single-page apps use resources from data APIs. You may want to restrict access to those resources, so that only authenticated users with sufficient privileges can access them. Auth0 lets you manage access to these resources using API Authorization.

This tutorial shows you how to access protected resources in your API.

This tutorial does not show you how to add protection to your API. Read the Backend/API quickstart documentation for instructions on how to protect your API.

Create a Resource Server (API)

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API. You will use the identifier later when you're configuring your Javascript Auth0 client instance. For Signing Algorithm, select RS256.

Create API

Add a Scope

By default, the access token does not contain any authorization information. To limit access to your resources based on authorization, you must use scopes. Read more about scopes in the scopes documentation.

In the Auth0 dashboard, in the APIs section, click Scopes. Add any scopes you need to limit access to your API resources.

You can give any names to your scopes. A common pattern is <action>:<resource>. The example below uses the name read:messages for a scope.

create scope

Set the Audience and Scope in auth0.WebAuth

In your auth0.WebAuth instance, enter your API identifier as the value for audience. Add your scopes to the scope key.

// src/app/auth/auth.service.ts

auth0 = new auth0.WebAuth({
  // ...
  audience: '{YOUR_API_IDENTIFIER}',
  scope: 'openid profile read:messages'
});

Checkpoint: Try to log in to your application again. Look at how the access_token differs from before. It is no longer an opaque token. It is now a JSON Web Token with a payload that contains your API identifier as the value for audience, and the scopes you created. Read more about this token in the JSON Web Tokens documentation.

By default, any user can ask for any scope you defined. You can implement access policies to limit this behavior using Rules.

Configure angular2-jwt

To give the authenticated user access to secured resources in your API, include the user's access token in the requests you send to your API. There are two common ways to do this.

  • Store the access token in a cookie. The access token is then included in all requests.
  • Send access_token in the Authorization header using the Bearer scheme.

The examples below use the Bearer scheme.

You can use the angular2-jwt module to automatically attach JSON Web Tokens to requests you make with Angular's Http class. The module provides an AuthHttp class which is a wrapper over the Http class.

Install angular2-jwt using npm or yarn.

# installation with npm
npm install --save angular2-jwt

# installation with yarn
yarn add angular2-jwt

Create a factory function with configuration values for angular2-jwt. Add the function to the providers array in your application's @NgModule. Add a tokenGetter function to the factory function to fetch the access token from local storage.

// src/app/app.module.ts

import { Http, RequestOptions } from '@angular/http';
import { AuthHttp, AuthConfig } from 'angular2-jwt';

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenGetter: (() => localStorage.getItem('access_token'))
  }), http, options);
}

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    AuthService,
    {
      provide: AuthHttp,
      useFactory: authHttpServiceFactory,
      deps: [Http, RequestOptions]
    }
  ],
  bootstrap: [...]
})

Make Authenticated Calls with AuthHttp

After you configure angular2-jwt, you can use the AuthHttp class to make secure calls to your API from anywhere in the application. Inject AuthHttp into any component or service and use it as you would use Angular's regular Http class. If you have an API that sends messages from the protected /private endpoint, you can create an API call.

// src/app/ping/ping.component.ts

import { AuthHttp } from 'angular2-jwt';
import 'rxjs/add/operator/map';

// ...
export class PingComponent {

  API_URL: string = 'http://<your-application-domain>/api';
  message: string;

  constructor(public authHttp: AuthHttp) {}

  public securedPing(): void {
    this.message = '';
    this.authHttp.get(`${this.API_URL}/private`)
      .map(res => res.json())
      .subscribe(
        data => this.message = data.message,
        error => this.message = error
      );
  }
}

To learn more about configuration options for angular2-jwt, see the main project repo.

Protect Your API Resources

To restrict access to the resources served by your API, check the incoming requests for valid authorization information. The authorization information is in the access token created for the user. To see if the token is valid, check it against the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating access tokens, read the Verify Access Tokens tutorial.

In each language and framework, you verify the access token differently. Typically, you use a middleware function to verify the token. If the token is valid, the request proceeds and the user gets access to resources in your API. If the token is invalid, the request is rejected with a 401 Unauthorized error.

The sample project shows how to implement this functionality using Node.js with the Express framework. To learn how to implement API protection for your server-side technology, see the Backend/API quickstart documentation.

Previous Tutorial
2. User Profile
Next Tutorial
4. Authorization
Use Auth0 for FREECreate free Account