# Autopopulate API keys

> Set up API key injection with JWT or OAuth authentication. Allow users to login and automatically populate their API keys in your API Explorer.

<Warning title="Pro and Enterprise feature">
  This feature is available only for the [Pro and Enterprise plans](https://buildwithfern.com/pricing). To get started, reach out to [support@buildwithfern.com](mailto:support@buildwithfern.com).
</Warning>

Fern can integrate with your authentication flow, allowing users to login and have their API key automatically populated with the click of a button.

<div>
  <iframe src="https://www.loom.com/embed/790eb5849f1c4622aae09527908fdc7a?sid=d77062f8-35c3-41ab-8669-4c28b62e233b?hide_owner=true&hide_share=true&hide_title=true&hideEmbedTopBar=true" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen />
</div>

With this feature, you can **create new users of your API** directly from within your documentation.

<Note>
  User credentials are stored only in browser cookies and never transmitted to Fern's servers. Learn more in the [Security overview](/learn/docs/security/overview).
</Note>

## Integrating with your auth flow

API key injection can work in two different ways depending on your company's authentication setup: **JWT or OAuth**.

* **JWT Flow:** You handle the entire auth flow and just give Fern a JWT cookie
* **OAuth Flow:** You give Fern access, and Fern directly initiates the OAuth handshake process

<AccordionGroup toc={true}>
  <Accordion title="JWT" toc={true}>
    ### How the JWT flow works

    To enable this feature, you need to configure authentication so that Fern can securely retrieve API keys for your users. The process works as follows:

    1. When a user clicks the "Login" button in the API Explorer, they're redirected to your authentication page.
    2. After successful authentication, your system must set a cookie called `fern_token` in the user's browser.
    3. This token should be a [JWT](https://jwt.io) encrypted with a secret key from Fern. The JWT should contain the user's API key.

    The JWT should have a structure similar to:

    <CodeBlocks>
      ```json Bearer
      {
        "fern": {
          "playground": {
            "initial_state": {
              "auth": {
                "bearer_token": "eyJhbGciOiJIUzI1c"
              }
            }
          }
        }
      }
      ```

      ```json Basic
      {
        "fern": {
          "playground": {
            "initial_state": {
              "auth": {
                  "basic": {
                    "username": "your_username",
                    "password": "your_password"
                  }
              }
            }
          }
        }
      }
      ```

      ```json Custom
      {
        "fern": {
          "playground": {
            "initial_state": {
              "headers": {
                "API-Version": "2024-02-02"
              },
              "path_parameters": {
                "id": "1234f"
              }, 
              "query_parameters": {
                "sort": "DESCENDING"
              }
            }
          }
        }
      }
      ```
    </CodeBlocks>

    #### Architecture diagram

    ```mermaid
    sequenceDiagram
        participant U as User
        participant F as Fern Docs
        participant R as Redirect URL
        participant A as Auth System

        U->>F: Visit restricted page
        F->>F: Check fern_token cookie
        
        alt Cookie exists
            F->>F: Decode JWT with secret key
            F->>F: Extract roles from JWT
            F->>F: Check if user has required role
            
            alt User has required role
                F->>U: Show restricted content
            else User lacks required role
                F->>U: User is shown a 404 page
            end
        else No cookie
            F->>R: Redirect to login page
            R->>A: Authenticate user
        end
        
        Note over A: User logs in
        
        A->>A: Generate JWT with roles
        A->>F: Set fern_token cookie
        F->>F: Validate JWT and roles
        F->>U: Show restricted content
    ```

    #### Setting up autopopulated API keys

    * [ ] Reach out to Fern to get your secret key
    * [ ] Send Fern the URL of your authentication page. This is where users will be redirected to after clicking the "Login" button in the API Explorer.
    * [ ] Add logic to your service to set the `fern_token` cookie when a user logs in

    <Tip>
      For an example of how to set up the 

      `fern_token`

       cookie, see this demo implementation 

      [here](https://github.com/fern-api/fern-platform/blob/app/packages/fern-docs/bundle/src/app/%5Bhost%5D/%5Bdomain%5D/api/fern-docs/auth/fern-token-demo/route.ts)

      .
    </Tip>
  </Accordion>

  <Accordion title="OAuth" toc={true}>
    ### How the OAuth flow works

    To enable this feature, you need to configure OAuth authentication so that Fern can securely retrieve API keys for your users through your OAuth provider. Here's how the process works:

    1. When a user clicks the "Login" button in the API Explorer, Fern initiates an OAuth flow by making a request to your authorization endpoint.
    2. The user is redirected to your OAuth provider's login page where they authenticate using your existing auth system.
    3. After successful authentication, your OAuth provider redirects back to Fern with an authorization code, which Fern exchanges for an access token at your token endpoint.
    4. Fern sets a `fern_token` cookie containing the user's authentication credentials and automatically populates their API key in the API Explorer.

    #### Architecture diagram

    ```mermaid
    sequenceDiagram
        participant U as User
        participant F as Fern Docs
        participant A as OAuth2 Provider
        U->>F: Visit restricted page
        F->>F: Check fern_token cookie
        
        alt Cookie exists
            F->>F: Decode cookie
            F->>F: Verify authentication credentials
            Note over F: Attempt to refresh the token, if expired
            
            alt User is properly authenticated
                F->>U: Show restricted content
            else User is not properly authenticated
                F->>U: User is shown a 404 page
            end
        else No cookie
            F->>A: Redirect to `/authenticate` endpoint
            A->>U: User authenticates
            U->>F: Authorization code is returned
            F->>A: Redirect to `/token` endpoint
            A->>A: Validate token request
            A->>F: Send authenticated access token
            F->>F: Set fern_token cookie
            F->>F: Verify authentication credentials
            F->>U: Show restricted content
        end
    ```

    #### Setting up autopopulated API keys

    To enable API key injection, you'll need to:

    * [ ] Set up an authenticated account for Fern so Fern can authorize users on your behalf.
    * [ ] Configure your OAuth application to return user API keys when Fern requests them

    Then, you'll need to send Fern the following items:

    * The client ID and client secret for Fern's authenticated account
    * The URL of your authentication endpoint. This is where users will be redirected to after clicking the "Login" button in the API Explorer.
    * The URL of your token endpoint. This is where Fern exchanges codes for tokens.
  </Accordion>
</AccordionGroup>