# Use a custom identity provider with @nylas/connect

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

`@nylas/connect` works with any identity provider that issues JWTs (JSON Web Tokens) and exposes a JWKS (JSON Web Key Set) endpoint. This means you can use open-source solutions like Keycloak or Ory, cloud services like Firebase Auth or Supabase Auth, or even your own custom JWT server.

If your identity provider isn't Auth0, Clerk, Google, or WorkOS, this is the guide for you.

## How JWKS works with Nylas

When you configure a custom identity provider, Nylas uses JWKS to verify the tokens your IdP issues:

1. Your IdP signs JWTs with a private key.
2. Your IdP exposes a JWKS endpoint (a public URL that serves the corresponding public keys).
3. When Nylas receives a request with your IdP token, it fetches the public keys from your JWKS endpoint and verifies the token signature.

This means Nylas never needs your IdP's private keys. It only needs the JWKS URL to verify that tokens are legitimate.

## Before you begin

You need an identity provider with JWKS support and a Nylas application configured to work together.


### 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.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.nylas.com/applications/<YOUR_APP_ID>/hosted-authentication/idp-settings
```


### Configure your JWKS endpoint in Nylas

In addition to the standard Nylas Dashboard setup, you need to provide your JWKS endpoint URL:

1. In the [Nylas Dashboard](https://dashboard.nylas.com), go to **Hosted Authentication** → **Identity Providers**.
2. Enter your IdP's **JWKS URI** (e.g., `https://your-idp.com/.well-known/jwks.json`).
3. Save the configuration.

### JWKS endpoint requirements

Your identity provider's JWKS endpoint must:

- Be publicly accessible over HTTPS (Nylas needs to fetch keys at runtime)
- Serve a valid JWKS JSON document with RSA or EC public keys
- Include the `kid` (key ID) header in issued JWTs that matches a key in the JWKS response
- Issue JWTs with a `sub` claim that uniquely identifies the user

Common JWKS endpoint paths by provider:

| Provider      | JWKS endpoint                                                                               |
| ------------- | ------------------------------------------------------------------------------------------- |
| Keycloak      | `https://<host>/realms/<realm>/protocol/openid-connect/certs`                               |
| Ory / Hydra   | `https://<host>/.well-known/jwks.json`                                                      |
| Firebase Auth | `https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com` |
| Supabase Auth | `https://<project-ref>.supabase.co/auth/v1/.well-known/jwks.json`                           |
| Custom server | Typically `https://your-domain.com/.well-known/jwks.json`                                   |

## Implementation

The pattern is the same as any other IdP integration: pass your token to `@nylas/connect` through the `identityProviderToken` callback. The specifics of how you obtain the token depend on your IdP.

Here's a generic example assuming your IdP provides a `getToken()` method:

```ts


async function getIdpToken(): Promise<string | null> {
  // Replace this with your IdP's token retrieval method.
  // Examples:
  //   Keycloak: keycloak.token
  //   Firebase: await firebase.auth().currentUser.getIdToken()
  //   Supabase: (await supabase.auth.getSession()).data.session?.access_token
  //   Custom:   await fetch("/api/auth/token").then(r => r.json()).then(d => d.token)
  return null;
}

const nylasConnect = new NylasConnect({
  clientId: "<NYLAS_CLIENT_ID>",
  redirectUri: "http://localhost:3000/auth/callback",
  identityProviderToken: async () => {
    try {
      return await getIdpToken();
    } catch (error) {
      console.error("Failed to get IdP token:", error);
      return null;
    }
  },
});

async function connectEmail() {
  try {
    const result = await nylasConnect.connect({ method: "popup" });
    console.log("Email connected:", result.grantInfo?.email);
  } catch (error) {
    console.error("Failed to connect email:", error);
  }
}

async function logout() {
  await nylasConnect.logout();
  // Also sign out from your IdP
}
```

### Keycloak example

```ts


const keycloak = new Keycloak({
  url: "https://your-keycloak-server.com",
  realm: "<REALM_NAME>",
  clientId: "<KEYCLOAK_CLIENT_ID>",
});

await keycloak.init({ onLoad: "login-required" });

const nylasConnect = new NylasConnect({
  clientId: "<NYLAS_CLIENT_ID>",
  redirectUri: "http://localhost:3000/auth/callback",
  identityProviderToken: async () => {
    await keycloak.updateToken(30);
    return keycloak.token || null;
  },
});
```

### Firebase Auth example

```ts


const auth = getAuth();

const nylasConnect = new NylasConnect({
  clientId: "<NYLAS_CLIENT_ID>",
  redirectUri: "http://localhost:3000/auth/callback",
  identityProviderToken: async () => {
    const user = auth.currentUser;
    if (!user) return null;
    return await user.getIdToken();
  },
});
```

## Make API calls

Your own identity system issues the token, so read the `sub` claim wherever you already track the signed-in user. If you only have the raw JWT, decode it base64url-safe: payloads use `-` and `_`, which `atob()` rejects, so the naive one-liner fails on a subset of tokens.

```ts
function decodeSub(token: string): string {
  const part = token.split(".")[1] ?? "";
  const base64 = part
    .replace(/-/g, "+")
    .replace(/_/g, "/")
    .padEnd(Math.ceil(part.length / 4) * 4, "=");
  return JSON.parse(atob(base64)).sub ?? "";
}

async function fetchEmails() {
  const token = await getIdpToken();

  const response = await fetch(
    "https://api.us.nylas.com/v3/grants/me/messages",
    {
      headers: {
        Authorization: `Bearer ${token}`,
        "X-Nylas-External-User-Id": decodeSub(token),
      },
    },
  );

  return await response.json();
}
```


Two headers do the work. `Authorization` carries your identity provider's access token, and `X-Nylas-External-User-Id` carries the user's `sub` claim, which is the same ID your application already stores. Nylas resolves `/v3/grants/me` to the mailbox linked to that ID, so no `grant_id` appears in the request.

The same 2 headers work across the Email, Calendar, and Contacts endpoints. Swap `/messages` for `/events` or `/contacts` and nothing else changes. For how the linkage is established, and when to use it instead of storing grant IDs, see [use your own user IDs instead of grant IDs](/docs/cookbook/use-cases/build/reuse-your-user-ids/).

> **Info:** 
> Use `https://api.us.nylas.com` for US-hosted applications, or `https://api.eu.nylas.com` for EU-hosted applications.


## Troubleshooting

| Problem                         | Cause                        | Solution                                                                                                                              |
| ------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `401 Unauthorized` on API calls | Nylas can't verify the token | Confirm your JWKS URI is correct and publicly accessible. Check that the `kid` in your JWT header matches a key in the JWKS response. |
| Token verification fails        | Key mismatch                 | Ensure your IdP is using the same key pair for signing tokens as the one published at the JWKS endpoint.                              |
| `sub` claim missing             | Token format issue           | Check that your IdP includes a `sub` claim in the JWT payload. Some IdPs use custom claim names.                                      |
| JWKS endpoint unreachable       | Network or CORS issue        | The JWKS endpoint must be publicly accessible over HTTPS. It doesn't need CORS headers because Nylas fetches it server-side.          |

## What's next

- [Session management](/docs/v3/auth/nylas-connect/use-external-idp/#session-management) for monitoring connection state
- [Error handling](/docs/v3/auth/nylas-connect/use-external-idp/#error-handling) for handling authentication failures
- [`@nylas/connect` overview](/docs/v3/auth/nylas-connect/) for standalone OAuth without an IdP
- [Auth0](/docs/v3/auth/nylas-connect/use-external-idp/auth0/), [Clerk](/docs/v3/auth/nylas-connect/use-external-idp/clerk/), [Google](/docs/v3/auth/nylas-connect/use-external-idp/google/), or [WorkOS](/docs/v3/auth/nylas-connect/use-external-idp/workos/) for provider-specific guides