> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ouim.me/llms.txt
> Use this file to discover all available pages before exploring further.

# verifyAuth

> Universal function for verifying Logto authentication tokens in any Node.js environment

## Overview

The `verifyAuth` function is a generic authentication verification utility that works in any Node.js environment. It can accept either a raw JWT token string or a request object with cookies and headers.

## Signature

```typescript theme={null}
async function verifyAuth(
  tokenOrRequest: string | { cookies?: any; headers?: any },
  options: VerifyAuthOptions
): Promise<AuthContext>
```

## Parameters

<ParamField path="tokenOrRequest" type="string | object" required>
  Either a JWT token string or a request object containing cookies and headers

  When passing an object:

  * `cookies`: Cookie object (e.g., from cookie-parser)
  * `headers`: Headers object or Headers API
</ParamField>

<ParamField path="options" type="VerifyAuthOptions" required>
  Configuration options for token verification

  <Expandable title="VerifyAuthOptions properties">
    <ParamField path="logtoUrl" type="string" required>
      Your Logto server URL (e.g., `https://your-logto.app`)
    </ParamField>

    <ParamField path="audience" type="string" required>
      Expected audience claim in the token (your application identifier)
    </ParamField>

    <ParamField path="cookieName" type="string" optional default="logto_authtoken">
      Name of the cookie containing the auth token
    </ParamField>

    <ParamField path="requiredScope" type="string" optional>
      Required OAuth scope that must be present in the token
    </ParamField>

    <ParamField path="allowGuest" type="boolean" optional default={false}>
      Allow guest access when no valid token is found. Returns guest context instead of throwing error
    </ParamField>
  </Expandable>
</ParamField>

## Returns

<ResponseField name="AuthContext" type="Promise<AuthContext>">
  Promise that resolves to authentication context

  <Expandable title="AuthContext properties">
    <ResponseField name="userId" type="string | null">
      User ID from the token's `sub` claim, or `null` for guest users
    </ResponseField>

    <ResponseField name="isAuthenticated" type="boolean">
      Whether the user is authenticated (`true`) or guest (`false`)
    </ResponseField>

    <ResponseField name="payload" type="AuthPayload | null">
      Decoded JWT payload, or `null` for guest users

      <Expandable title="AuthPayload properties">
        <ResponseField name="sub" type="string">
          User ID (subject claim)
        </ResponseField>

        <ResponseField name="scope" type="string">
          OAuth scopes granted to the token
        </ResponseField>

        <ResponseField name="[key: string]" type="any">
          Additional claims in the JWT payload
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="isGuest" type="boolean" optional>
      `true` if this is a guest context (only when `allowGuest: true`)
    </ResponseField>

    <ResponseField name="guestId" type="string" optional>
      Unique identifier for guest users (auto-generated UUID)
    </ResponseField>
  </Expandable>
</ResponseField>

## Throws

* Throws an error if no token is found and `allowGuest` is `false`
* Throws an error if token verification fails and `allowGuest` is `false`
* When `allowGuest: true`, returns guest context instead of throwing

## Examples

### With JWT Token String

```typescript theme={null}
import { verifyAuth } from '@ouim/logto-authkit/server'

const token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...'

try {
  const auth = await verifyAuth(token, {
    logtoUrl: 'https://your-logto.app',
    audience: 'https://api.yourapp.com'
  })

  console.log('User ID:', auth.userId)
  console.log('Authenticated:', auth.isAuthenticated)
} catch (error) {
  console.error('Authentication failed:', error)
}
```

### With Request Object (Generic)

```typescript theme={null}
import { verifyAuth } from '@ouim/logto-authkit/server'

const request = {
  cookies: { logto_authtoken: 'eyJhbGciOiJ...' },
  headers: { authorization: 'Bearer eyJhbGciOiJ...' }
}

const auth = await verifyAuth(request, {
  logtoUrl: process.env.LOGTO_URL,
  audience: process.env.LOGTO_AUDIENCE
})

if (auth.isAuthenticated) {
  console.log('User:', auth.userId)
  console.log('Scopes:', auth.payload?.scope)
}
```

### With Guest Support

```typescript theme={null}
import { verifyAuth } from '@ouim/logto-authkit/server'

const auth = await verifyAuth(request, {
  logtoUrl: process.env.LOGTO_URL,
  audience: process.env.LOGTO_AUDIENCE,
  allowGuest: true // Won't throw if no token found
})

if (auth.isGuest) {
  console.log('Guest user:', auth.guestId)
} else {
  console.log('Authenticated user:', auth.userId)
}
```

### With Required Scope

```typescript theme={null}
import { verifyAuth } from '@ouim/logto-authkit/server'

try {
  const auth = await verifyAuth(token, {
    logtoUrl: process.env.LOGTO_URL,
    audience: process.env.LOGTO_AUDIENCE,
    requiredScope: 'admin:write' // Requires this scope
  })

  // Token has admin:write scope
  console.log('Admin user:', auth.userId)
} catch (error) {
  console.error('Missing required scope')
}
```

### Custom Cookie Name

```typescript theme={null}
import { verifyAuth } from '@ouim/logto-authkit/server'

const auth = await verifyAuth(request, {
  logtoUrl: process.env.LOGTO_URL,
  audience: process.env.LOGTO_AUDIENCE,
  cookieName: 'my_custom_auth_cookie'
})
```

## Token Extraction Order

When a request object is provided, tokens are extracted in this order:

1. Cookie (using `cookieName` option, defaults to `logto_authtoken`)
2. Authorization header (Bearer token)

The first valid token found is used for verification.

## Verification Process

The function performs the following verification steps:

1. Fetches JWKS (JSON Web Key Set) from your Logto server
2. Decodes JWT header to identify the signing key
3. Verifies JWT signature using the public key
4. Validates token claims:
   * Issuer (`iss`) matches Logto URL
   * Audience (`aud`) matches provided audience
   * Token is not expired (`exp`)
   * Token is valid (`nbf` - not before)
   * Required scope is present (if specified)

## Caching

JWKS (signing keys) are cached for 5 minutes to reduce requests to the Logto server and improve performance.

## See Also

* [createExpressAuthMiddleware](/logto-authkit/api/server/create-express-auth-middleware) - Express.js middleware
* [verifyNextAuth](/logto-authkit/api/server/verify-next-auth) - Next.js authentication helper
* [useAuth](/logto-authkit/api/hooks/use-auth) - React hook for client-side authentication
