AngularJS Calling an API

Sample Project

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

System Requirements
  • AngularJS 1.6
Show requirements

It's likely that your single page app will need to consume resources from a data API. Since you are adding authentication to your app, presumably you need to limit access to these resources such that they are only accessible by an authenticated user who is authorized to retrieve them. Auth0 provides API Authorization to accomplish this.

This tutorial will guide you through how to make calls from your application to your data API to access protected resources. It does not, however, cover how to add protection to your API itself. For instructions on protecting your API, please follow the Backend/API quickstart documentation specific to your situation.

Create a Resource Server (API)

In the APIs section of the Auth0 Dashboard, click the Create API button. Provide a Name and Identifier for your API and be sure to choose the RS256 signing algorithm. The identifier you set will later be used as the audience when configuring your auth0.WebAuth instance.

Create API

Add a Scope

When an access_token is received after a user authenticates in your app, it is simply an indication that they have proven their identity. By default, however, the access_token does not contain any authorization information. To properly limit access to your resources based on authorization, you must use scopes.

In the settings area for your API within the Auth0 dashboard, navigate to the Scopes tab. Add any scopes necessary to limit access to your API resources. While the naming of the scopes is at your discretion, a common pattern is to use <action>:<resource>. The example here will use a read:messages scope.

create scope

Set the Audience and Scope

Pass the API identifier for your newly created API as the audience value to angularAuth0Provider. Additionally, pass any of your newly created scopes to the scope key.

// app/app.js

angularAuth0Provider.init({
  audience: '{YOUR_API_IDENTIFIER}',
  scope: 'openid profile read:messages'
});

At this point you should try logging into your application again to take note of how the access_token differs from before. Instead of being an opaque token, it is now a JSON Web Token which has a payload that contains your API identifier as an audience and any scopes you've requested.

By default, any user on any client can ask for any scope defined in the scopes configuration area. You can implement access policies to limit this behaviour via Rules.

Configure angular-jwt

To access secured resources from your API, the authenticated user's access_token needs to be included in requests that are sent to it. This is typically accomplished either by sending the access_token in an Authorization header using the Bearer scheme or by storing the token in a cookie so that it is included in all requests to your server. These example will focus on the former implementation, but both approaches are valid.

The angular-jwt module can be used to automatically attach JSON Web Tokens to requests made with Angular's $http service.

If you haven't already done so, install angular-jwt.

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

# installation with yarn
yarn add angular-jwt

Reference the angular-jwt module from your application's main module and inject jwtOptionsProvider and $httpProvider. Specify a tokenGetter function in the provider which retrieves the user's access_token from local storage so that it can be attached as an Authorization header. Whitelist any domains you wish to enable authenticated $http calls for. Finally, push the jwtInterceptor into the $httpProvider.interceptors array.

// app/app.js

(function () {

  'use strict';

  angular
    .module('app', ['auth0.auth0', 'angular-jwt', 'ui.router'])
    .config(config);

  config.$inject = [
    // ...
    '$httpProvider',
    'jwtOptionsProvider'
  ];

  function config(
    // ...
    $httpProvider,
    jwtOptionsProvider
  ) {

    jwtOptionsProvider.config({
      tokenGetter: function() {
        return localStorage.getItem('access_token');
      },
      whiteListedDomains: ['localhost']
    });

    $httpProvider.interceptors.push('jwtInterceptor');
  }

})();

Make Authenticated Calls with $http

With the jwtInterceptor in place, the user's access_token will automatically be attached to $http calls when they are made. You can now make $http calls as you normally would and, because the user's access_token will be included in the call, protected API resources will be accessible to them.

// app/ping/ping.controller.js

(function () {

  'use strict';

  angular
    .module('app')
    .controller('PingController', pingController);

  pingController.$inject = ['$http', 'authService'];

  function pingController($http, authService) {

    var API_URL = 'http://localhost:3001/api';
    var vm = this;
    vm.auth = authService;
    vm.message = '';

    vm.securedPing = function() {
      vm.message = '';
      $http.get(API_URL + '/private').then(function(result) {
        vm.message = result.data.message;
      }, function(error) {
        vm.message = error;
      });
    }

  }

})();

To find out more about configuration options for angular-jwt, see the main project repo.

How Do I Protect my API Resources?

To restrict access to the resources served by your API, a check needs to be made to determine whether the incoming request contains valid authorization information. When you implement Auth0 in your client-side application and data API, that authorization information is the access_token issued for your user. This token must be checked against the JSON Web Key Set (JWKS) for your Auth0 account to verify that it is valid.

The exact way in which access_token verification is implemented on your server will vary between languages and frameworks; however, a common pattern involves placing the token verification logic in a middleware function. If the access_token is valid, the request should proceed. If it is invalid, the request should be rejected with a 401 Unauthorized error.

The downloadable sample linked above demonstrates how to accomplish this implementation using Node.js with the Express framework. For instructions on how to implement API protection for the specific server-side technology you are using, see the Backend/API quickstart documentation.

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