Manage grants
In Nylas v3, "Grants" replace the concept of "Connected Accounts". Each grant represents an end user and the scopes that they have granted your application access to. For more information on changes in v3, see v3 Authentication changes and the terminology changes documentation.
Grants are the main objects that power Nylas v3, so you'll be working with them often. This page describes how to manage grants for your Nylas applications.
How grants work
A grant is a record of a specific end user's account authenticating successfully with their provider, and "granting" Nylas access to specific parts of their account's email inbox and calendar (represented by authentication "scopes"). A valid grant records a unique ID for the end user, the scopes that they granted during authentication, and some information about access tokens for the grant.
Before you begin
💡 Follow the v3 Quickstart guide to get your environment up and running.
Before you can manage your Nylas application's grants, you must have the following set up:
- A provider authentication app.
- At least one grant associated with your application.
- Administrator access to your Nylas application.
Keep in mind
Remember that each grant belongs to a specific connector in a specific Nylas application. A grant cannot be associated with multiple connectors, providers, or applications.
Create a grant
You can create grants in two ways in Nylas v3: using Hosted OAuth or Custom auth.
🔍 Nylas creates only one grant per email address in each application. If an end user authenticates with your Nylas application using the email address associated with an existing grant, Nylas re-authenticates the grant instead of creating a new one.
Create a grant using Hosted OAuth
If you're using Hosted OAuth with an API key, the rough process for creating a grant is as follows:
- The end user clicks a link or button in your Nylas application to start an OAuth request.
- Nylas forwards the end user to their auth provider where they complete the OAuth flow, either accepting or declining the requested scopes.
- The auth provider directs the user to the Nylas callback URI, and includes URL parameters that indicate whether auth was successful and other information.
- If auth was successful, Nylas creates an unverified grant record, then forwards the user to your application's
callback_uri
. The accesscode
from the provider is included as a parameter in the URL. - Your application uses the
code
to perform a token exchange with the provider. - When the token exchange completes successfully, Nylas marks the grant record as verified and sends the
grant_id
to you.
If you're using Hosted OAuth with an access token, the process is much the same as the above. At the end, though, the end user's code
is exchanged for an access token. Nylas then marks the grant as verified and sends the grant_id
to you.
Create a grant using Custom auth
If you're using Custom auth, you authenticate the end user using your own process and pass their credentials (for example, a refresh token or IMAP username and password) to Nylas. Nylas then creates a grant for the end user, and sends the grant_id
to you.
Example API response
When you create a grant, Nylas sends you JSON response similar to the following snippet.
{
"request_id": "5967ca40-a2d8-4ee0-a0e0-6f18ace39a90",
"data": {
"id": "e19f8e1a-eb1c-41c0-b6a6-d2e59daf7f47",
"provider": "microsoft",
"grant_status": "valid",
"email": "leyah@hotmail.com",
"scope": [
"Mail.Read",
"User.Read",
"offline_access"
],
"user_agent": "string",
"ip": "string",
"state": "my-state",
"created_at": 1617817109,
"updated_at": 1617817109
}
}
Re-authenticate a grant
Grants can become invalid for many reasons (for example, the end user changing their password or revoking their access to your Nylas application). When grants become invalid, they must be re-authenticated to allow end users access to your application.
When a grant becomes invalid, Nylas loses access to the affected user's data and stops sending notifications about changes to its objects. When the end user re-authenticates, Nylas looks at when their grant last authenticated successfully. If it was less than 72 hours ago, Nylas looks for any changes that happened since the last successful sync and sends you notifications about those events. This can be a lot of notifications.
If the grant was out of service for more than 72 hours, Nylas doesn't send backfill notifications. When this happens, look for the grant.expired
and grant.updated
notifications and query the Nylas APIs for objects that changed between those timestamps.
⚠️ If message tracking events occur while a grant is out of service for more than 72 hours, you cannot backfill the notifications. This includes message.opened
, message.link_clicked
, and thread.replied
notifications.
Re-authenticating a grant follows the same flow and uses the same APIs as initial authentication. When Nylas receives an auth request, it checks to see if a grant is already associated with the end user's email address. If one exists, Nylas re-authenticates the grant instead of creating a new one.
Monitor grants for invalid state
You can use one of the following methods to monitor grants for an invalid state using the Nylas APIs:
- (Recommended) Subscribe to notifications with
grant.*
triggers to stay up to date with status changes. If you receive agrant.expired
notification, the affected grant needs to be re-authenticated. - Make poll requests to the Grants endpoint and check the
grant_status
. If the API returns a401
error code response, the affected grant needs to be re-authenticated.
To see a list of authenticated grants and their status, log in to the v3 Dashboard and select Grants in the left navigation menu. Grants that need to be re-authenticated are marked as Invalid.
Prompt end user to re-authenticate
When you encounter an invalid grant, the end user must re-authenticate using the email address associated with their grant.
If you're using Hosted OAuth, you can redirect the end user to the /v3/connect/auth
endpoint. They're then redirected to the provider, where they review your Nylas application's requested scopes and either accept or decline them.
If you're using Custom auth, you can redirect the end user to the /v3/connect/custom
endpoint to handle their authentication using your auth flow.
Delete a grant
If a user no longer needs access to your application, you can delete their grant by making a DELETE /v3/grants/<NYLAS_GRANT_ID>
request. Nylas also revokes the refresh token and any access tokens associated with the grant. If you're deleting a Google grant, Nylas also revokes its provider tokens. For all other providers, the provider tokens remain active.
⛔️ When you make a Delete Grant request, Nylas deletes the grant and stops sending notifications for it. You cannot re-authenticate the deleted grant. If you try to re-authenticate it, Nylas creates a new grant instead.
Delete a grant with Nylas SDKs
You can use the Nylas SDKs to delete grants, as in the following samples.
package com.nylas
import com.nylas.NylasClient
import com.nylas.models.DeleteResponse
fun main() {
try {
val nylas = NylasClient.Builder("<NYLAS_API_KEY>").build()
// ID of the existing user grant to be deleted.
val grantId = "<NYLAS_GRANT_ID>"
val response: DeleteResponse = nylas.auth().grants().destroy(grantId)
if (response.requestId != null) {
println("User grant with id $grantId is successfully deleted.")
}
}
}
import * as dotenv from "dotenv";
import Nylas from "nylas";
import inquirer from "inquirer";
dotenv.config();
const nylas = new Nylas({
apiKey: process.env.NYLAS_API_KEY
});
async function main() {
const grants = await nylas.auth.grants.list();
try {
const answer = await inquirer.prompt([
{
type: "list",
name: "grants",
message: "Select an email to delete:",
choices: grants.data.map(({ email, id }) => ({
name: email,
value: {
id,
email
}
}))
}
]);
const { requestId } = await nylas.grants.destroy({
grantId: answer.grants.id
});
console.log("Grants deleted successfully!");
}
}
import base64
import os
from datetime import datetime
import nylas
from dotenv import load_dotenv
from nylas.models.grants import (Grant, ListGrantsQueryParams)
from nylas.models.response import ListResponse, Response
load_dotenv()
def list_grants(
client: nylas.Client, query_params: ListGrantsQueryParams
) -> ListResponse[Grant]:
try:
grants, _, _ = client.auth.grants.list(query_params)
return grants
def delete_grant(client: nylas.Client, grant_id: str) -> None:
try:
delete_response = client.auth.grants.destroy(grant_id)
print(f"\nGrant with ID {grant_id} deleted successfully.")
Delete a grant in v3 Dashboard
Follow these steps to delete a grant in the v3 Dashboard:
- Click Grants in the left navigation menu.
- On the Grants screen, find the grant that you want to delete and click the options symbol (
⋮
) beside it. - Click Delete and confirm that you want to delete the grant.
Revoked versus deleted grants
A grant can be revoked in multiple scenarios (for example, the end user changed their password). When a grant is revoked, its token is invalidated and the end user cannot access your Nylas application until they re-authenticate. Nylas also cannot update the data for a revoked grant.
Nylas stores the data for grants so long as they are associated with your application, even if their access has been revoked. Nylas deletes a grant's data only when the grant itself is deleted.
📝 Nylas bills for all grants associated with your application, even if they are revoked. When you delete a grant, your organization is no longer billed for it. For more information, see the Billing documentation.
Referencing grants in API requests
You can locate grants authenticated to your application in any of the following ways:
-
Using the
grant_id
. This is the simplest method, and the format that you see throughout the docs. -
Using the
/me/
construction and an access token in your API call. Nylas uses the access token to find the grant it's associated with, and uses thegrant_id
internally.curl --request GET \
--url https://api.us.nylas.com/v3/grants/me/messages/ \
--header 'Accept: application/json' \--header 'Authorization: Bearer <NYLAS_ACCESS_TOKEN>' \
--header 'Content-Type: application/json' -
Using an authenticated email address in place of the grant ID.
curl --request GET \
--url https://api.us.nylas.com/v3/grants/nyla@example.com/messages/ \
--header 'Accept: application/json' \
--header 'Authorization: Bearer <NYLAS_API_KEY>' \
--header 'Content-Type: application/json'
Working with grants in the v3 Dashboard
You can also see a list of each application's grants from the Nylas Dashboard.
From the Grants page, you can view the status of your end users' grants, see their details, and revoke them if needed. You can use this page to filter grants by different attributes, and check their details to help diagnose end user problems and troubleshoot permissions issues.
You can also create a test grant, which allows you to test your authentication configuration settings. You still need a correctly configured connector before you can authenticate a test account to create a grant.