Instantly Connect 100% Of Email Accounts With Hosted Auth

Learn how to integrate Nylas Hosted Auth and connect 100% of email providers to your app, including Gmail, Office 365, Outlook, Exchange, and more.

Ben Lloyd Pearson | August 13, 2020

If you’re building an app that needs to incorporate email functionality that keeps information updated in real-time, there’s a good chance you’ve investigated direct IMAP integrations and the overwhelming number of email API offerings from the likes of Gmail, Exchange, Office 365, Outlook, and more. They each have their own unique methods for integrating, so you might be asking yourself where to get started. Even once you’ve sorted through the chaotic protocols and behemoth APIs, it takes on average 30,000 hours and over $2M to build out a connection to all the major providers.

You can build a full integration faster and at a fraction of the cost using the Nylas Email API. Nylas provides a single point of integration that connects your app to every single email account in the world. This article will demonstrate how to use Nylas Hosted Auth to authenticate user email accounts into your app. We take care of the complexities related to auto-detecting service providers and negotiating and maintaining access to third-party services.  This lets you focus on building the features your users love rather than navigating the complex documentation of third-party integrations. It also enables your users to leverage the data and functionality of their own email accounts, no matter their preferred service provider.

Want a PDF of this article?

Share it with a friend or save it for later reading.

Get Started 

To demonstrate how Nylas Hosted Auth works, we’ve built Inbox Zero, a demo application you can run to explore and understand the Nylas Email API. It’s built using:

  • Next.js, a framework for making server-rendered React apps
  • Express.js to create RESTful endpoints on the server
  • JSON Web Tokens (JWT) for authentication and session management
  • Lowdb, a lightweight key-value database powered by Lodash, for storing user information
  • The Nylas Node SDK, a client helper library that makes it easy to leverage the Nylas Platform.

These are combined to produce a demo that demonstrates the entire process of authenticating a user email account into your app so you can start building email functionality immediately.

Nylas Hosted Auth with Inbox Zero

To get ready to run this app, you’ll first need to download the git repo, and switch to the hosted-auth branch that was created for this specific article:

git clone https://github.com/nylas/inbox-zero.git && cd inbox-zero
git checkout hosted-auth

Set Up Your Nylas Account

First thing first: before you can do any coding, you need a Nylas account. If you don’t have one already, register now for a free 30-day trial. You can use the app that comes preconfigured with your Nylas account, or set up your own. Once you’ve created your account, take note of the Client ID and Client Secret for your Nylas App, we’ll need them in a moment.

Inbox Zero stores the Nylas client ID and secret as environment variables, along with a secret that will be used to sign JWTs. For easy environment management, copy the .example-env file found in the repos top level directory to a file named .env. Then, add your Nylas App client ID and secret to the appropriate lines and create a unique string for the JWT_SECRET variable.

One last thing to consider: some providers have stricter requirements for user access. If you want to connect Google or Office365 accounts to Nylas, follow the setup instructions found at those links. Before you attempt to login to the Inbox Zero app, you’ll also need to register the callback address for the app with Nylas. In the Nylas dashboard, head to All Applications, press the Edit button next to your app, and add http://localhost:3000/api/authorize under the Callbacks tab. You’ll only have to do this once.

Once all of this is done, run the following commands from the terminal, inside the Inbox Zero git repo to run the app.

npm install
npm run local
You should now be able to access the Inbox Zero app by visiting http://localhost:3000 in your web browser.

How Nylas Hosted Auth Works

The basis for the authentication flow in Inbox Zero is Nylas Hosted Auth, which takes a three-legged approach to authentication: 

  1. The user is directed to the Nylas Hosted Auth service. Once there, Nylas handles email provider auto-detection and the appropriate process to negotiate access with the third-party email service provider. 
  2. The user is directed back to your application with a one-time code. 
  3. Your app exchanges the one-time code for an access token that can be used to access email data and functionality for the user account.

Illustration of the Nylas Hosted Auth service that integrates with 100% of email, calendar, and contacts providers, including Google

Let’s take a look at how this is implemented in Inbox Zero.

Construct the User Login Flow

Now that we have our Nylas app set up and ready to go, it’s time to start building our app’s front-end. The first thing we need to setup is a login form for our user to connect their email account. When the user submits the form, their email address is sent to the login route, which constructs a unique URL for the Nylas Hosted Auth Service and redirects the user to this URL. The auth URL contains information about our app, as well as the user that’s signing in, so it’ll be unique for each user. Fortunately, the Nylas Node SDK has a built in function to generate the URL.

To properly construct an auth URL we need 3 things:

  1. redirectURI: The URL where Nylas should direct the user once authentication is complete; this must match the URL you added to the Callbacks settings. Since we’re running Inbox Zero locally, we’ll use http://localhost:3000 as the hostname. In Inbox Zero, the route that handles the authentication response is /api/authorize.
  2. loginHint: The email address the user submits through the app’s login form.
  3. scopes: A list of the permissions the app is requesting to obtain. Inbox Zero let’s you read, modify, and send emails, and schedule appointments. So we’ll request email.read_only, email.modify, email.send, and calendar permissions.

Here is the code that accomplishes this:

const Nylas = require('nylas');
Nylas.config({
    clientId: process.env.NYLAS_ID,
    clientSecret: process.env.NYLAS_SECRET
});

const options = {
    redirectURI: "http://localhost:3000/api/authorize",
    loginHint: emailAddress,
    scopes: ["email.read_only", "email.modify", "email.send", "calendar"]
};
const authUrl = Nylas.urlForAuthentication(options);

All that’s left to do is send the redirect to our generated URL, and they’ll be on their way!

res.redirect(authUrl);

From there, the Nylas Platform determines the email provider and drops the user into the correct login flow. 

Authenticate Email Accounts with Nylas Hosted Auth

Create an Access Token for the Email Account

Once the user finishes the email provider’s login flow, Nylas redirects the user to the Inbox Zero app at the authorization route. This new redirect URL includes a query parameter that provides a one-time code issued by Nylas; this code then needs to be exchanged for an access token via the Nylas Node SDK:

const code = req.query.code;
const accessToken = await Nylas.exchangeCodeForToken(code);

The access token will be used to access the user’s account within the requested scopes. For example, the app displays the user’s email address in the header:

const nylas = Nylas.with(accessToken);
const { emailAddress } = await nylas.account.get();

Secure the Access Token with Lowdb and JSON Web Tokens

This access token needs to be stored for as long as the app is performing actions on behalf of the user; in the case of Inbox Zero, we want to store it until the user logs out. To do so, we’ll save it to a database using  the cache helper module to access the Lowdb instance:

const cache = require("./utils/cache");
await cache.set(emailAddress, accessToken);

When the app receives requests for that email address, it looks up the appropriate access token in the database. But, how does the app know that the person contacting the site is the same as the person it originally authenticated? This is where JSON Web Tokens come into play.JWTs are great because they let you store information and verify authenticity in a single operation. This token will be handed to the user and the user will pass it back to the app with each request. First,  generate a JWT with a claim for the user’s email address:

const token = jwt.sign({ emailAddress }, process.env.JWT_SECRET);

To figure out which user is making the request, verify the signature and extract the emailAddress claim. For example:

const { emailAddress } = jwt.verify(token, process.env.JWT_SECRET);

And since the JWT secret is only known to the app, no one else can forge a token. In Inbox Zero, the token is handed to the user by setting a cookie in the response from the callback page. With this, their browser will automatically send it with each request the user makes. There’s no need for extra authentication logic on the front end! 

res.cookie("token", token, {
    path: "/",
    httpOnly: false
});

Now that we’ve fully handled the authentication process, it’s time to send the user to the home page for the app:

res.redirect("/");

Log Out and Revoke Tokens

There’s still one step missing in our authorization model: logging out. When a user clicks the sign out button, they’ll be directed to the logout route. To secure their information, the app will revoke the access token the app has stored.
// Retrieve the user's access token
const accessToken = await cache.get(emailAddress);
// Use the access token to fetch the user's account
const nylas = Nylas.with(accessToken);
const account = await nylas.account.get();
const fullAccount = await Nylas.accounts.find(account.id);
// Revoke access tokens
await fullAccount.revokeAll();

And, just like that, the access token has been invalidated. Finally, clearing the cookie that holds the JWT will prevent the app from treating the user as if they’re still signed in.

res.clearCookie("token", { path: "/" });
res.redirect("/login");
And, voila! We now have a complete authentication model that works for 100% of email providers.

Build More Email Functionality With Nylas

The Nylas Platform is the easiest way to add full email functionality to your app, and with the information in this article, you’re now ready to connect 100% of email accounts to your app. But why stop there? With Nylas, developers also unlock the full capability of users’ calendars and contact books, and these combined with email functionality allow you to turn your app into a scheduling powerhouse. Let Nylas be the backend for your next email, calendar, and contacts integration and free up more time to focus on the features your users love.

Ben Lloyd Pearson

Ben is the Developer Advocate for Nylas. He is a triathlete, musician, avid gamer, and loves to seek out the best breakfast tacos in Austin, Texas.