Angular: Call an API

Gravatar for steve.hobbs@auth0.com
By Steve Hobbs

This tutorial demonstrates how to make API calls to the Auth0 Management API. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to integrate with my app

15 minutes
  1. Provide the HTTP Interceptor
  2. Make an API Call
Or

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: Angular 12+

The focus of this guide is to show you how to configure the SDK to call APIs protected by OAuth 2. Instead of creating a demo API to test the client-server connection, you'll use the Auth0 Management API, which comes bundled with your Auth0 tenant. However, you can adapt this guide to work with any API that you are securing with Auth0.

This article builds upon the previous chapter, adding the capability to automatically attach an access token to outgoing requests made using Angular's built-in HttpClient service.

Provide the HTTP Interceptor

To install and configure the HTTP interceptor, perform the following steps:

  • Import the authHttpInterceptorFn type from the Auth0 Angular SDK
  • Import provideHttpClient from @angular/common/http
  • Register authHttpInterceptorFn in provideHttpClient using withInterceptors.
  • Add configuration to specify audience, scope, and which requests should have an Authorization header attached automatically

The following is an example of an Angular module (based upon the default implementation when you create a new app using ng new) that supports AuthHttpInterceptor, configured to call the Auth0 Management API with the ability to read the current user profile:

To begin, open your app.module.ts file and add the necessary imports at the top:

// Import the injector module and the HTTP client module from Angular
import { provideHttpClient, withInterceptors } from '@angular/common/http';

// Import the HTTP interceptor from the Auth0 Angular SDK
import { authHttpInterceptorFn } from '@auth0/auth0-angular';

Was this helpful?

/

Next, add provideHttpClient to the providers of the bootstrapApplication function, and add authHttpInterceptorFn using withInterceptors:

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(withInterceptors([authHttpInterceptorFn])),
  ]
});

Was this helpful?

/

Finally, modify the configuration given to provideAuth0() to specify the audience and scope values required by the API you want to call, as well as the API routes that should be intercepted by authHttpInterceptorFn.

In this case, the audience and scope for the Auth0 Management API are given, which allows your app to retrieve information about the current user.

provideAuth0({
  // The domain and clientId were configured in the previous chapter
  domain: '{yourDomain}',
  clientId: '{yourClientId}',

  authorizationParams: {
    redirect_uri: window.location.origin,
    
    // Request this audience at user authentication time
    audience: 'https://{yourDomain}/api/v2/',

    // Request this scope at user authentication time
    scope: 'read:current_user',
  },

  // Specify configuration for the interceptor              
  httpInterceptor: {
    allowedList: [
      {
        // Match any request that starts 'https://{yourDomain}/api/v2/' (note the asterisk)
        uri: 'https://{yourDomain}/api/v2/*',
        tokenOptions: {
          authorizationParams: {
            // The attached token should target this audience
            audience: 'https://{yourDomain}/api/v2/',

            // The attached token should have these scopes
            scope: 'read:current_user'
          }
        }
      }
    ]
  }
})

Was this helpful?

/

Please refer to the docs for more information on the available options for the HTTP interceptor.

Make an API Call

With your app module configured with the HTTP interceptor from the Angular SDK, calls you make using Angular's built-in HttpClient to the Auth0 Management API will have the appropriate access token specified in the Authorization header. Let's use this as an example for showing user metadata.

The following component demonstrates how to display the user_metadata field from the authenticated user's profile, by making a call to the /api/v2/users endpoint using HttpClient:

import { Component, OnInit } from '@angular/core';
import { concatMap, tap, map } from 'rxjs/operators';

// Import the HttpClient for making API requests
import { HttpClient } from '@angular/common/http';

// Import AuthService from the Auth0 Angular SDK to get access to the user
import { AuthService } from '@auth0/auth0-angular';

@Component({
  selector: 'app-metadata',
  template: `<div *ngIf="metadata">
    <pre>{{ metadata | json }}</pre>
  </div>`,
  standalone: true,
})
export class UserMetadataComponent implements OnInit {
  metadata = {};

  // Inject both AuthService and HttpClient
  constructor(public auth: AuthService, private http: HttpClient) {}

  ngOnInit(): void {
    this.auth.user$
    .pipe(
      concatMap((user) =>
        // Use HttpClient to make the call
        this.http.get(
          encodeURI(`https://{yourDomain}/api/v2/users/${user?.sub}`)
        )
      ),
      map((user: any) => user.user_metadata),
      tap((meta) => (this.metadata = meta))
    )
    .subscribe();
  }
}

Was this helpful?

/

This call succeeds because the HTTP interceptor took care of making sure the correct access token was included in the outgoing request.

Checkpoint

Your application will show an empty JSON object if you have not set any user_metadata for the logged-in user. To further test out this integration, head to the Users section of the Auth0 dashboard and click on the user who is logged in. Update the user_metadata section with a value like { "theme": "dark" } and click "Save". Refresh your Angular application and verify that it reflects the new user_metadata.

Please refer to the Auth0 API quickstarts to learn how to integrate Auth0 with your backend platform.

More Angular tutorials

Did it work?

Any suggestion or typo?

Edit on GitHub