Ember

Community maintained

Sample Project

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

Before you start

This guide walks you through setting up authentication and authorization in your Ember apps with Auth0. If you are new to Auth0, check our Overview. For a complete picture of authentication and authorization for all Single Page Applications, check our SPA + API documentation.

Auth0 uses OAuth. If you want to learn more about the OAuth flows used by Single Page Applications, read about Authentication for Client-side Web Apps.

Get Your Application Keys

When you signed up for Auth0, you created a new client.

Your application needs some details about this client to communicate with Auth0. You can get these details from the Settings section for your client in the Auth0 dashboard.

You need the following information:

  • Client ID
  • Domain

If you download the sample from the top of this page, these details are filled out for you. If you have more than one client in your account, the sample comes with the values for your Default App.

App Dashboard

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.

You need to whitelist the callback URL for your app in the Allowed Callback URLs field in your Client Settings. If you do not set any callback URL, your users will see a mismatch error when they log in.

If you are following along with the sample project, Allowed Callback URLs should be set to http://localhost:4200.

Install auth0.js

You need the auth0.js library to integrate Auth0 into your application.

Install auth0.js using npm or yarn.

# installation with npm
npm install --save auth0-js

# installation with yarn
yarn add auth0-js

Once you install auth0.js, add it to your build system or bring it in to your project with a script tag.

<script type="text/javascript" src="node_modules/auth0-js/build/auth0.js"></script>

If you do not want to use a package manager, you can retrieve auth0.js from Auth0's CDN.

<script src="https://cdn.auth0.com/js/auth0/8.10.1/auth0.min.js"></script>

Add Authentication with Auth0

The Auth0 hosted login page is the easiest way to set up authentication in your application. We recommend using the Auth0 hosted login page for the best experience, best security and the fullest array of features. This guide will use it to provide a way for your users to log in to your Ember application.

You can also embed the Lock widget directly in your application. If you use this method, some features, such as single sign-on, will not be accessible.

When a user logs in, Auth0 returns three items:

You can use these items in your application to set up and manage authentication.

Create an Authentication Service

The best way to manage and coordinate the tasks necessary for user authentication is to create a reusable service. With the service in place, you'll be able to call its methods throughout your application. The name for it is at your discretion, but in these examples it will be called auth and the filename will be auth.js. An instance of the WebAuth object from auth0.js can be created in the service.

Create a service and instantiate auth0.WebAuth. Provide a method called login which calls the authorize method from auth0.js.

// app/services/auth.js

import Ember from 'ember';
import config from 'auth0-ember-samples/config/environment';

const {
  computed,
  Service,
  get
} = Ember;

export default Service.extend({
  auth0: computed(function () {
    return new auth0.WebAuth({
      domain: 'YOUR_AUTH0_DOMAIN',
      clientID: 'YOUR_CLIENT_ID',
      redirectUri: 'http://localhost:4200',
      audience: 'https://YOUR_AUTH0_DOMAIN/userinfo',
      responseType: 'token id_token',
      scope: 'openid'
    });
  }),

  login() {
    get(this, 'auth0').authorize();
  }
});

Checkpoint: Try calling the login method from somewhere in your application. This could be from a button click or in some lifecycle event, just something that will trigger the method so you can see the login page.

hosted login

Finish Out the Authentication Functions

Add some additional methods to the auth service to fully handle authentication in the app.

// app.js

import Ember from 'ember';
import config from 'auth0-ember-samples/config/environment';

const {
  computed,
  Service,
  get,
  RSVP,
  isPresent,
} = Ember;

export default Service.extend({

  // ...
  handleAuthentication() {
    return new RSVP.Promise((resolve, reject) => {
      get(this, 'auth0').parseHash((err, authResult) => {
        if (authResult && authResult.accessToken && authResult.idToken) {
          this.setSession(authResult);
        } else if (err) {
          return reject(err);
        }

        return resolve();
      });
    });
  },

  isAuthenticated: computed(function() {
    return isPresent(this.getSession().access_token) && this.isNotExpired();
  }).volatile(),

  getSession() {
    return {
      access_token: localStorage.getItem('access_token'),
      id_token: localStorage.getItem('id_token'),
      expires_at: localStorage.getItem('expires_at')
    };
  },

  setSession(authResult) {
    if (authResult && authResult.accessToken && authResult.idToken) {
      // Set the time that the access token will expire at
      let expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
      localStorage.setItem('access_token', authResult.accessToken);
      localStorage.setItem('id_token', authResult.idToken);
      localStorage.setItem('expires_at', expiresAt);
    }
  },

  logout() {
    // Clear access token and ID token from local storage
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
  },

  isNotExpired() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = this.getSession().expires_at;
    return new Date().getTime() < expiresAt;
  }
});

The file now includes several other methods for handling authentication.

  • handleAuthentication - looks for an authentication result in the URL hash and processes it with the parseHash method from auth0.js
  • setSession - sets the user's access_token, id_token, and a time at which the access_token will expire
  • logout - removes the user's tokens from browser storage
  • isAuthenticated - checks whether the expiry time for the access_token has passed

About the Authentication Service

When you set up the AuthService service, you create an instance of the auth0.WebAuth object. In that instance, you can define the following:

  • Configuration for your client and domain
  • Response type, to show that you need a user's access token and an ID token after authentication
  • Audience and scope, which specify that authentication must be OIDC-conformant
  • The URL where you want to redirect your users after authentication.

In this tutorial, the route is /callback, which is implemented in the Add a Callback Component step.

Your users authenticate at the Auth0 hosted login page. They are then redirected back to your application. Their redirect URLs contain hash fragments with each user's authentication information:

  • access_token
  • id_token
  • expires_in

You can get the tokens from the URL using the parseHash method in the auth0.js library. You can save the values in local storage with the setSession method. The setSession method uses the expires_in value from the URL hash fragment to calculate when the user's access token expires.

Authentication using JSON Web Tokens is stateless. This means that when you use it, no information about the user's session is stored on your server.

To set up a session for the user on the client side, save the following information in browser storage:

  • access_token
  • id_token
  • expires_in

To log the user out, you must remove these values from the storage.

The examples below use local storage to save the user's authentication information. You can also use session storage or cookies.

You need to provide a way for your application to recognize if the user is authenticated. To do that, use the isAuthenticated method to check if the user's access token has expired. The user is no longer authenticated when the expiry time of their access token passes.

Provide a Login Control

Provide a template with controls for the user to log in and log out.

<!-- app/templates/index.hbs -->

<div>
  <a href="#" class="login" {{action "login"}}>Log In</a>
</div>

The action added to the Log In control makes the appropriate call to the login method in auth.js to allow the user to log in. When the Log In control is clicked, the user will be redirected to Auth0's hosted login page.

The Auth0 hosted login page uses the Lock widget. To learn more about the hosted login page, see the hosted login page documentation. To customize the look and feel of the Lock widget, see the customization options documentation.

Process the Authentication Result

When a user authenticates at Auth0's hosted login page and is then redirected back to your application, their authentication information will be contained in a URL hash fragment. The handleAuthentication function in auth.js is responsbile for processing the hash.

Call handleAuthentication in app.js so that the authentication hash fragment can be processed when the app first loads after the user is redirected back to it.

// app/routes/application.js

import Ember from 'ember';

const {
  Route,
  inject: {
    service,
  },
  get,
} = Ember;

export default Route.extend({
  auth: service(),
  beforeModel() {
    if (get(this, 'auth.isAuthenticated')) {
      return;
    }

    return get(this, 'auth')
      .handleAuthentication()
      .then(() => {
        if (get(this, 'auth.isAuthenticated')) {
          this.transitionTo('protected')
        }
      });
  },
});

Create a Protected Route

After a user authenticates and returns to your application, you may wish to send them to a protected route. The transition logic is demonstrated above in the transitionTo call after authentication. Add a new route called protected and check whether the user is authenticated before allowing them to see it.

// app/routes/protected.js

import Ember from 'ember';

const {
  Route,
  inject: {
    service,
  },
  get,
} = Ember;

export default Route.extend({
  auth: service(),
  beforeModel() {
    if (!get(this, 'auth.isAuthenticated')) {
      return this.replaceWith('application');
    }
  }
});

Add a template for this route.

<!-- app/templates/protected.hbs -->

<a href="#" {{action "logout"}}>
    Log Out
</a>
<br/>
<h2>You are logged in!</h2>

Notice that there is also a Log Out control in this route which has an action of logout. This will call the logout method on the auth service allowing the user to log out.

Embedded Login

Auth0's hosted login page provides the fastest, most secure, and most feature-rich way to implement authentication in your app. If required, the Lock widget can also be embedded directly into your application, but certain features such as single sign-on won't be accessible. It is highly recommended that you use the hosted login page (as covered in this tutorial), but if you wish to embed the Lock widget directly in your application, follow the Embedded Login sample.

Use Auth0 for FREECreate free Account