​The Easiest Way to Add Authentication to Any App

TL;DR: Implementing authentication in modern web apps is a pain, but it doesn't have to be. Auth0 is the easiest way to add authentication to your app and you can get started easily with a free plan that includes up to 7,000 regular active users and two social providers. A user is considered active if they've logged in sometime in the last 30 days. For a lot of companies, that's only 15% of their user base. Read on to learn more about the challenges of modern authentication and how Auth0 solves them!

auth0 lock

The Problem with Modern Authentication

Authentication is an essential part of nearly all non-trivial applications and is a very important thing to get right. As developers, we've been able to enjoy a lot of great improvements to the web in recent years, but unfortunately, implementing authentication in our apps hasn't been one of them. There are a few key reasons for this, including:

  • A shifting identity landscape where we are now logging in with social providers like Google, Facebook, Twitter, and others
  • A desire for tighter security through features like multi-factor authentication, passwordless login, and single sign-on
  • A new approach for application architecture that makes it more difficult to implement authentication

Social Authentication

There are a number of open source libraries out there (such as PassportJS for Node) that do a great job of making it easier to add social authentication to apps. However, this can still mean a fair bit of set up and configuration for the developer to manage.

Modern Authentication Features

Features like passwordless login and single sign-on are growing in popularity. If you've logged into Slack from mobile, you've probably seen the option of being sent a "magic link" to authenticate. This is really convenient for accessing the app quickly, especially if you've got a long and complex password.

If you've worked in a large organization that uses a lot of different apps, you might know the pain of needing to authenticate against each one of them. This is solved with single sign-on, which allows users to access multiple apps with the same set of credentials.

Multi-factor authentication​, which is also referred to as two-step verification, is now being used widely as an extra layer of security. Implementations of this feature vary, but in general, when the user logs in to an app, they are sent a verification code via text message (or through an app like Google Authentictor) that they must enter to proceed.

These two features are great, but are difficult to implement and can be error-prone.

Authentication for Single Page Apps

Session and cookie-based authentication can still be made to work in modern single page apps, but this method can break down quickly and generally doesn't scale well. Instead, if we're building apps with frameworks like Angular, React, Vue, Ember, and others, it is arguably best to authenticate users with JSON Web Tokens (JWT). This method is much more flexible and scalable than others, and has been widely adopted.

While JWT authentication is great for modern apps, it comes at the cost of being time consuming to implement. Wiring up all the pieces on the front-end and backend can require a lot of effort and create delays in project timelines.

The Easiest Way to Implement Modern Authentication

Auth0 solves all the above mentioned problems for you by providing an identity and authentication service that takes the pain out of implementing auth in modern apps. You can use any social authentication provider and implement features like multi-factor auth and single sign-on, all at the flip of a switch. This is huge because instead of focusing your development effort on making sure the authentication process is right, you can concentrate on building your actual application.

Auth0 can be used in web and mobile apps with nearly any front-end and backend combination and is perfect for both SPAs and traditional web apps. There are a lot of ready-to-go integrations available for almost any language and framework with excellent documentation.

New Pricing == Tons of Value for Free!

At Auth0, we love to make developers' lives easier. As part of this committment, we just launched a new pricing plan that gives you a ton of value at no cost. For absolutely free, you can use two social providers and authenticate up to 7,000 regular active users with unlimited logins. A regular active user is one that has logged in sometime in the last 30 days. For a lot of companies, this only accounts for 15% of their userbase! This is perfect if you want to create a minimum viable product quickly without paying anything for a third party authentication service.

Just How Easy Is It?

Auth0 has integrations for nearly all popular frameworks and languages. Not using a framework? No problem! For web apps, all you really need is some JavaScript. Let's see how easy it is to get going. We'll set things up for a vanilla JavaScript single page app in this case, but you can also use Auth0 for traditional round-trip apps too.

Step 0: Sign Up for Auth0

Sign up for your free account to follow along with these steps!

Step 1: Add the Auth0Lock Script

Lock is our login box widget that comes fully ready to use. You can bring it in from our CDN, or you can find it on NPM.

<!-- index.html -->

  <!-- Auth0Lock script -->
  <script src="https://cdn.auth0.com/js/lock-8.1.min.js"></script>

  <!-- Setting the right viewport -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

Step 2: Configure Auth0Lock

Configure Auth0Lock by creating an instance of the service.

// app.js

var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_DOMAIN');

Step 3: Implement the Login

The first thing you'll need is a login button that will trigger the Lock widget.

<!-- index.html -->

  ...

  <button id="btn-login" class="btn-login">Sign In</button>

  ...

Now you can add an event listener to that button that will open up Lock.

// app.js

document.getElementById('btn-login').addEventListener('click', function() {
  lock.show(function(err, profile, token) {
    if (err) {
      // Error callback
      console.error("Something went wrong: ", err);
    } else {
      // Success calback  

      // Save the JWT token.
      localStorage.setItem('userToken', token);
      // Save the profile
      localStorage.setItem('userProfile', JSON.stringify(profile));
    }
  });
});

Now when the Sign In button is clicked, the Lock widget will be shown.

auth0 lock

You can sign up a test user and log them in with the Lock widget. When the user is logged in, their token and profile will be saved in local storage.

auth0 devtools

Note: Make sure to add your test domain (http://localhost:9000 in this case) to the Allowed Origins in your Auth0 dashboard.

Step 4: Make Authenticated Calls to an API

With the user's token in local storage, you can now make authenticated calls to your API by attaching the JWT as an Authorization header.

// app.js

var getFoos = fetch('/api/foo', {
  headers: {
    'Authorization': 'Bearer ' + localStorage.getItem('userToken')
  },
  method: 'GET',
  cache: false
});

getFoos.then(function (response) {
  response.json().then(function (foos) {
    console.log('the foos:', foos);
  });
});

This example uses the Fetch API, but you can use plain XHR calls or other libraries for making XHR calls as well.

Step 5: Add Logout

All you need to do to log the user out is remove their token and profile from local storage.

// app.js

localStorage.removeItem('userToken');
localStorage.removeItem('userProfile');
window.location.href = "/";

And that's it! You've got authentication set up on the front end. You'll also need to set up JWT middleware on your protected API routes. This can be done easily with our integrations for backends like NodeJS.

Popular Integrations

We have SDKs for popular frameworks, libraries, and languages to save you time:

Front End

Backend

Mobile

Wrapping Up

Adding authentication to your app is very easy with Auth0. With a free plan that provides username/password database and two social providers for up to 7,000 regular active users, Auth0 is the easiest way to get up and running quickly.

If you haven't done so already, sign up for a free account today! You can also check out our pricing plans to see our other packages.

Say hi to us on Twitter and shoot us an email if you need any help getting going.

This content is sponsored via Syndicate Ads.

Ryan Chenkie

Tech Writer at Auth0 where I create tutorials on the latest web technologies. I also write about Angular, Laravel and more on my site. Say hi to me Twitter!