# Using external identity providers with Nylas Connect

Source: https://developer.nylas.com/docs/v3/auth/nylas-connect/use-external-idp/

You can integrate external identity providers (IDPs) with Nylas Connect to authenticate users through your existing identity system. This links your users' IDP identities with their Nylas grants, so you can make Nylas API calls using your IDP tokens without managing separate authentication flows.

## Supported identity providers

Nylas Connect works with any identity provider that issues JWTs and exposes a JWKS endpoint. These guides cover the most popular options:

| Provider       | Description                                                                     | Guide                                                                          |
| -------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| **Auth0**      | Enterprise authentication platform with support for social logins, MFA, and SSO | [Auth0 integration](/docs/v3/auth/nylas-connect/use-external-idp/auth0/)       |
| **Clerk**      | Modern authentication with prebuilt UI components and session management        | [Clerk integration](/docs/v3/auth/nylas-connect/use-external-idp/clerk/)       |
| **Google**     | OAuth 2.0 authentication via Google Identity Services                           | [Google integration](/docs/v3/auth/nylas-connect/use-external-idp/google/)     |
| **WorkOS**     | Enterprise SSO, directory sync, and multi-factor authentication                 | [WorkOS integration](/docs/v3/auth/nylas-connect/use-external-idp/workos/)     |
| **Custom IDP** | Any identity provider with a JWKS endpoint (Keycloak, Ory, custom JWT servers)  | [Custom IDP integration](/docs/v3/auth/nylas-connect/use-external-idp/custom/) |

> **Using React?:** 
> Each provider guide shows vanilla JavaScript examples. For React implementations with `useNylasConnect`, see the [React external IDP guides](/docs/v3/auth/nylas-connect-react/use-external-idp/).

## How it works

When you use an external IDP with Nylas Connect, the authentication flow has five steps:

1. **User authenticates with your IDP**: The user signs in through your identity provider (Auth0, Clerk, Google, WorkOS, etc.).
2. **IDP provides an access token**: Your IDP returns a JWT access token representing the authenticated user.
3. **Configure Nylas Connect**: You pass the IDP token to Nylas Connect using the `identityProviderToken` callback.
4. **User connects their email account**: Nylas opens an OAuth flow for the email provider (Google, Microsoft, etc.) and links the resulting grant to the user's IDP identity.
5. **Make API calls**: You use the IDP token as a Bearer token in Nylas API requests, along with the `X-Nylas-External-User-Id` header.

## Before you begin


### Configure Nylas Dashboard

Before connecting your identity provider, configure the IDP settings in the Nylas Dashboard:

1. Navigate to your application in the [Nylas Dashboard](https://dashboard-v3.nylas.com).
2. Go to **Hosted Authentication** → **Identity Providers**.
3. Configure the following settings:
   - **Allowed Origins**: Add the domains where your application will be hosted (e.g., `http://localhost:3000`, `https://yourapp.com`). These origins will be allowed to make requests to Nylas with your IDP tokens.
   - **Callback URIs**: Add the redirect URIs that Nylas will use after authentication (e.g., `http://localhost:3000/auth/callback`). These must match the `redirectUri` configured in your NylasConnect instance.

> **Note:** 
> The allowed origins and callback URIs are security measures to prevent unauthorized use of your Nylas application. Include all domains where your application will run, including development, staging, and production environments.

You can access the Identity Provider settings page directly at:

```
https://dashboard-v3.nylas.com/applications/<YOUR_APP_ID>/hosted-authentication/idp-settings
```


## Configuration

To use an external IDP, configure your `NylasConnect` instance with an `identityProviderToken` function. This function must return the current user's IDP access token as a string:

```ts


const nylasConnect = new NylasConnect({
  clientId: "<NYLAS_CLIENT_ID>",
  redirectUri: "http://localhost:3000/auth/callback",
  identityProviderToken: async () => {
    // Return the IDP access token for the current user
    return await getIdpToken();
  },
});
```

The `identityProviderToken` callback is called every time Nylas Connect needs to authenticate a request. Your IDP SDK typically handles token refresh automatically, so this function should always return a fresh token.

## Session management

These methods work the same regardless of which IDP you use:

```ts
// Check connection status
const status = await nylasConnect.getConnectionStatus();
console.log("Status:", status); // "connected" | "expired" | "invalid" | "not_connected"

// Get session information
const session = await nylasConnect.getSession();
if (session?.grantInfo) {
  console.log("Connected as:", session.grantInfo.email);
  console.log("Provider:", session.grantInfo.provider);
  console.log("Grant ID:", session.grantId);
}

// Listen for connection state changes
nylasConnect.onConnectStateChange((event, session, data) => {
  switch (event) {
    case "CONNECT_SUCCESS":
      console.log("Successfully connected:", session?.grantInfo?.email);
      break;
    case "CONNECT_ERROR":
      console.error("Connection failed:", data?.error);
      break;
    case "CONNECT_CANCELLED":
      console.log("User cancelled authentication");
      break;
  }
});
```

## Error handling

Handle errors when connecting email accounts through Nylas Connect:

```ts
try {
  const result = await nylasConnect.connect({ method: "popup" });
  console.log("Connection successful:", result);
} catch (error) {
  if (error.name === "PopupError") {
    console.error("Popup was blocked or closed");
  } else if (error.name === "ConfigError") {
    console.error("Configuration error:", error.message);
  } else if (error.name === "OAuthError") {
    console.error("OAuth error:", error.message);
  } else {
    console.error("Unexpected error:", error);
  }
}
```

## Best practices

- **Token refresh**: Ensure your `identityProviderToken` function returns fresh tokens. Most IDP SDKs handle token refresh automatically.
- **Error handling**: Always handle cases where the IDP token is unavailable or expired.
- **Secure storage**: Store tokens securely and never expose them in client-side code that could be compromised.
- **Session persistence**: Use `persistTokens: true` in your Nylas Connect configuration to maintain sessions across page reloads.
- **User experience**: Provide clear feedback when authentication fails or when users need to re-authenticate with either the IDP or email provider.