Skip to content

Create grants with OAuth and an access token

This page describes how to use the OAuth 2.0 features included in Nylas v3 with a user’s access token to create a grant.

If you’re using Hosted Authentication and developing a Single Page App (SPA) or mobile app, Nylas recommends you use the OAuth 2.0 with PKCE authentication method. This extra layer of security adds a key to the authentication exchange that you can safely store on a mobile device instead of including the API key. This is optional for projects that have a backend, but it’s a good security practice to implement it anyway.

Using /me/ syntax to refer to a grant

Nylas v3 uses the /me/ syntax that you use in access token-authorized API calls instead of specifying a user’s grant ID (for example, GET /v3/grants/me/messages).

The /me/ syntax looks up the grant associated with the request’s access token, and uses the grant_id associated with the token as a locator. You can use this syntax for API requests that access account data only, and only if you use access tokens to authorize requests. You can’t use this syntax if you’re using API key authorization, because there is no grant associated with an API key.

For more information, see /me/ syntax for API calls.

Before you begin

Before you begin, make sure you set up all the required parts for your authentication system:

  1. If you haven’t already, log in to the v3 Dashboard and create a Nylas application.
  2. Generate an API key for your application in the v3 Dashboard.
  3. Create a provider auth app in the provider’s console or application. See the detailed instructions for creating a Google or Azure provider auth app.
  4. Create a connector for the provider you want to authenticate with.
  5. Add your project’s callback URIs (“redirect URIs”) in the Nylas Dashboard.

Create grants with OAuth and an access token

Make authorization request

The first step of the OAuth process is to collect the information you need to include when starting an authorization request. You usually start the request using either a button or link that the user clicks, which redirects them to api.us.nylas.com/v3/connect/auth and includes their information. The example below requests two scopes using a Google provider auth app.

/v3/connect/auth?
client_id=<NYLAS_CLIENT_ID>
&redirect_uri=<REDIRECT_URI>
&response_type=code
&provider=google
&access_type=offline
&state=sQ6vFQN

This request also uses the optional access_type=offline parameter to specify that Nylas should return a refresh token. The rendered URL that the user is directed to resembles the example below.

https://accounts.google.com/o/oauth2/auth/oauthchooseaccount?
client_id=<GCP_CLIENT_ID> // The client ID from your Google auth app.
&prompt=consent
&redirect_uri=https://api.us.nylas.com/connect/callback
&response_type=code
&scope=https://www.googleapis.com/auth/gmail.readonly%20profile
&access_type=offline
&state=BA630DED06... // Stored and checked/compared internally by Nylas for security.

You can also start the authorization process using the Nylas SDKs, as in the examples below.

The user goes to the URL Nylas starts a secure authentication session and redirects the user to the provider website.

Each provider displays the consent and approval steps differently, and it’s only visible to the end-user. In all cases the user authenticates, then either accepts or declines the scopes your project requested.

Authorization response and grant creation

Next, the auth provider sends the user to the Nylas redirect_uri (https://api.us.nylas.com/v3/connect/callback), and includes information about the outcome of the session as query parameters in the URL.

Nylas uses the information in the response to find your Nylas application by client_id and, if the auth was successful, create an unverified grant record for the user and record their details.

Get the user’s code

Nylas uses your project’s callback_uri (for example, app.example.com/callback-handler) to send the user back to your project. The callback URI includes query parameters to indicate to your project if authentication was successful.

The example below shows parameters for a successful authentication. The code and state query parameters are standard OAuth 2.0 fields, but Nylas provides some optional fields to give you more context about the authentication.

https://myapp.com/callback-handler?
state=... // Passed value of initial state if it was provided.
&code=... // Use this code value for the next step of authentication.

Exchange code for access token

Next, exchange the code for an access token. Make a POST /v3/connect/token request and include the code parameter from the success response.

POST /token HTTP/1.1
Host: /v3/connect/token
Content-Type: application/json
{
"code": "<AUTH_EXCHANGE_CODE>",
"client_id": "<NYLAS_CLIENT_ID>",
"client_secret": "<NYLAS_API_KEY>",
"redirect_uri": "<REDIRECT_URI>",
"grant_type": "authorization_code"
}

The auth provider responds with an access token, a refresh token (because you asked for one by setting access_type=offline when you made the authorization request), and some other information. When the user completes the authentication flow successfully, Nylas marks their grant as verified and sends you their grant_id and email address.

Your application should store the grant_id, the access_token, and refresh_token (for later re-authentication).

{
"access_token": "<ACCESS_TOKEN>",
"refresh_token": "<REFRESH_TOKEN>",
"scope": "https://www.googleapis.com/auth/gmail.readonly profile",
"token_type": "Bearer",
"id_token": "<ID_TOKEN>",
"grant_id": "<NYLAS_GRANT_ID>"
}

You can also exchange the user’s code using the Nylas SDKs.

Authorize API calls with access token and /me/ syntax

When you have an end user’s access token, you can use it to authorize API requests for that user’s data, and that user’s data only. You can’t use an access token to authorize API requests that access or modify data at the application level. Those requests require an API key for authorization.

To authorize an API request, pass the token in the request header using HTTP Bearer authentication, then substitute the word me in the API calls where you would usually specify a grant_id.

When Nylas receives a request using the /me/ syntax, it checks the authorization header token, finds the grant_id associated with that token, and uses that ID to locate data for the user.

The examples below illustrate an API request using an access token and the /me/ syntax, and the equivalent call using the grant_id.

(Optional) Refresh an expired access token

If you set access_type=offline in the initial authorization request, Nylas returns a refresh_token along with the access_token during the token exchange. When the initial access_token expires, you can use the refresh_token to request a new one.

Make a POST /v3/connect/token request that specifies "grant_type": "refresh_token" and includes the refresh token, as in the example below. The auth provider returns a fresh access token.

You can also use the Nylas SDKs to refresh an access token.

Create grants with OAuth 2.0 and PKCE

The OAuth PKCE (Proof Key for Code Exchange) flow improves security for client-side-only applications, such as browser-based or mobile apps that don’t have a back-end server. Even if your application does have a back-end server, Nylas recommends you use PKCE for extra security.

Never store application-wide credentials like API keys in mobile or client-side code. Instead, complete the code exchange flow without using your Nylas application’s API key. If you’re using PKCE, you can set the platform parameter to android, desktop, ios, or js when you create a callback URI to make the client_secret field optional.

The following sections describe how to create grants using OAuth 2.0 and PKCE.

Construct a code challenge

Before you make an authentication request using PKCE, you need to create a code_challenge. You’ll use this when you make authorization requests.

The following example uses nylas as a code verification string and sets the encoding method to S256 for extra security.

  1. Hash the verification string using an SHA-256 encoding tool (SHA256("nylas") -> e96bf6686a3c3510e9e927db7069cb1cba9b99b022f49483a6ce3270809e68a2).
  2. Convert the hashed string to Base64 encoding and remove any padding (e96bf6686a3c3510e9e927db7069cb1cba9b99b022f49483a6ce3270809e68a2 -> ZTk2YmY2Njg2YTNjMzUxMGU5ZTkyN2RiNzA2OWNiMWNiYTliOTliMDIyZjQ5NDgzYTZjZTMyNzA4MDllNjhhMg).
  3. Save the resulting encoded string to use as the code_challenge in your authorization request.

Make authorization request with code challenge

Next, make a GET /v3/connect/auth request to create a URL that redirects your end user to the auth flow.

/connect/auth?
client_id=<NYLAS_CLIENT_ID>
&redirect_uri=https://myapp.com/callback-handler
&response_type=code
&provider=google
&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly%20profile
&state=sQ6vFQN
&code_challenge=ZTk2YmY2Njg2YTNjMzUxMGU5ZTkyN2RiNzA2OWNiMWNiYTliOTliMDIyZjQ5NDgzYTZjZTMyNzA4MDllNjhhMg
&code_challenge_method=S256

You can also make an authorization request using the Nylas SDKs, as in the following examples.

Exchange authorization code for access token

The rest of the OAuth flow should proceed as usual: the end user is redirected to the auth provider, where they authenticate and accept or reject the requested scopes. The provider then sends them back to Nylas with an authorization code, and Nylas creates an unverified grant. Nylas returns the end user to your project with the code.

Use the code in a POST /v3/connect/token request to get an access token. Because you’re using PKCE, you must set the grant_type to authorization_code and include your code_verifier string.

For readability, the example below sets code_verifier to the original plain text code_verifier value.

POST /token HTTP/1.1
Host: /v3/connect/token
Content-Type: application/json
{
"client_id": "<NYLAS_CLIENT_ID>",
"redirect_uri": "<REDIRECT_URI>",
"grant_type": "authorization_code",
"code": "<AUTH_EXCHANGE_CODE>",
"code_verifier": "nylas"
}

You can also exchange the code for an access token using the Nylas SDKs, as in the following examples.

Handling authentication errors

If authentication fails, Nylas returns the standard OAuth 2.0 error fields in the response: error, error_description, and error_uri.

https://myapp.com/callback-handler?
state=... // Passed value of initial state if it was provided
&error=... // Error type/constant
&error_description=... // Error description
&error_uri=... // Error or event code

If an unexpected error occurs during the callback URI creation step at the end of the flow, the response includes an error_code field instead of an error_uri.

https://myapp.com/callback-handler?
&error=internal_error // Error type/constant
&error_description=Internal+error%2C+contact+administrator // Error description
&error_code=500 // Code of internal error

Using access_type to request refresh tokens

You can use the access_type parameter in your token exchange request to indicate whether you want Nylas to return a refresh token for the grant.

If your project is a mobile or client-side-only app, Nylas recommends you use access_type=online. This prevents the OAuth process from creating a refresh token, so you must prompt the user to re-authenticate when their access token expires.

If your project isn’t mobile or client-side-only, you can use access_type=offline to get a refresh token when a user authenticates. You can use the refresh token to get a new access token for the user without prompting them to re-authenticate.

Using the state parameter to pass information about the user

Nylas Hosted OAuth includes the standard state parameter. This is an optional parameter in Nylas, and if you include it in an authorization request, Nylas returns the value unmodified back to the application. You can use this as a verification check, and to track information about the user that you need when creating a grant or logging them in.

Learn more about the state parameter in the OAuth 2.0 specification or in the official OAuth 2.0 documentation.