AngularJS: Calling an API

View on Github

AngularJS: Calling an API

Gravatar for andres.aguiar@auth0.com
By Andres Aguiar
Auth0

This tutorial demonstrates how to make API calls for protected resources on your server. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

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

View on Github
System requirements: AngularJS 1.6+

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 an 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 application 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

Configure your Application

In the angularAuth0Provider.init call, enter your API identifier as the value for audience. Set the scopes in the scope parameter.

// app/app.js

angularAuth0Provider.init({
  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 angular-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 angular-jwt module to automatically attach JSON Web Tokens to requests you make with Angular's $http service.

Install angular-jwt using npm or yarn.

# 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. Inject jwtOptionsProvider and $httpProvider. In the provider, specify a tokenGetter function which retrieves the user's Access Token from local storage. The token can then be attached as an Authorization header.

Whitelist any domains you want to enable authenticated $http calls for. Push 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');
  }

})();

Call the API

With jwtInterceptor in place, the user's Access Token is automatically attached to $http calls. When you make $http calls, your protected API resources become accessible to the user.

// 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.data.message || error.data;
      });
    }

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

})();

To learn more about configuration options for angular-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.

Use Auth0 for FREE