> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/pensarai/apex/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Authenticate against target systems and manage session credentials

## Overview

The Authentication API provides intelligent authentication capabilities that handle various login mechanisms including form-based auth, OAuth, API tokens, and complex multi-step flows. It securely manages credentials and exports session data for use in subsequent testing.

**Key Features:**

* Automatic credential management via CredentialManager
* Support for multiple auth schemes (forms, OAuth, JWT, API keys)
* Browser automation for complex login flows
* CSRF and anti-bot handling
* Email verification support
* Secure credential storage with no raw secrets in prompts
* Session export (cookies, headers, tokens)

***

## runAuthenticationAgent

Authenticate against a target and persist the session for subsequent operations.

**Authentication Flow:**

1. Agent navigates to the target/login page
2. Detects authentication mechanism
3. Uses browser tools to fill forms and interact with auth flows
4. Handles CSRF tokens, CAPTCHAs, email verification
5. Validates successful authentication
6. Exports cookies and headers
7. Persists auth data to session directory

```typescript theme={null}
import { runAuthenticationAgent } from '@pensar/apex/api/authentication';

// Credentials are managed automatically via session config
const result = await runAuthenticationAgent({
  target: 'https://app.example.com',
  model: 'claude-sonnet-4-20250514',
  session: sessionInfo,  // Session with authCredentials configured
});

if (result.success) {
  console.log('Authentication successful!');
  console.log(`Strategy: ${result.strategy}`);
  console.log(`Cookies: ${result.exportedCookies}`);
}
```

### Parameters

<ParamField path="input" type="AuthenticationAgentInput" required>
  Configuration for the authentication agent

  <Expandable title="AuthenticationAgentInput properties">
    <ParamField path="target" type="string" required>
      The target URL requiring authentication (typically the login page or base URL)
    </ParamField>

    <ParamField path="model" type="AIModel" required>
      AI model identifier (e.g., `"claude-sonnet-4-20250514"`)
    </ParamField>

    <ParamField path="session" type="SessionInfo" required>
      Session object. When created with `authCredentials` in the config, a CredentialManager is automatically provisioned. The agent reads credentials via credential IDs — raw secrets never appear in prompts.
    </ParamField>

    <ParamField path="authHints" type="object">
      Optional hints about the authentication flow to guide the agent

      <Expandable title="authHints properties">
        <ParamField path="authScheme" type="string">
          Expected auth scheme (e.g., `"form"`, `"oauth2"`, `"bearer"`, `"api-key"`)
        </ParamField>

        <ParamField path="csrfRequired" type="boolean">
          Whether CSRF protection is detected
        </ParamField>

        <ParamField path="browserRequired" type="boolean">
          Whether browser automation is needed (for JS-heavy SPAs)
        </ParamField>

        <ParamField path="protectedEndpoints" type="string[]">
          List of endpoints that require authentication (for verification)
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField path="authConfig" type="AIAuthConfig">
      Optional per-provider API key overrides
    </ParamField>

    <ParamField path="abortSignal" type="AbortSignal">
      AbortSignal to cancel authentication mid-run
    </ParamField>

    <ParamField path="onStepFinish" type="StreamTextOnStepFinishCallback">
      Callback fired after each agent step completes
    </ParamField>

    <ParamField path="callbacks" type="ConsumeCallbacks">
      Stream event callbacks for monitoring authentication progress

      <Expandable title="ConsumeCallbacks properties">
        <ParamField path="onTextDelta" type="(delta) => void">
          Called for each text chunk streamed from the AI
        </ParamField>

        <ParamField path="onToolCall" type="(delta) => void">
          Called when the agent invokes a tool
        </ParamField>

        <ParamField path="onToolResult" type="(delta) => void">
          Called when a tool execution completes
        </ParamField>

        <ParamField path="onError" type="(error) => void">
          Called when an error occurs
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

### Response

<ResponseField name="success" type="boolean">
  Whether authentication was successful
</ResponseField>

<ResponseField name="summary" type="string">
  Human-readable summary of the authentication process
</ResponseField>

<ResponseField name="exportedCookies" type="string">
  Session cookies in HTTP Cookie header format (e.g., `"session=abc123; csrf=xyz456"`)
</ResponseField>

<ResponseField name="exportedHeaders" type="Record<string, string>">
  Additional headers required for authenticated requests (e.g., Authorization tokens)

  Example:

  ```json theme={null}
  {
    "Authorization": "Bearer eyJhbGc...",
    "X-CSRF-Token": "abc123"
  }
  ```
</ResponseField>

<ResponseField name="strategy" type="string">
  Authentication strategy used (e.g., `"form-based"`, `"oauth2"`, `"api-key"`, `"session-cookies"`)
</ResponseField>

<ResponseField name="authBarrier" type="AuthBarrier | undefined">
  Details about any authentication barrier encountered during the process

  <Expandable title="AuthBarrier properties">
    <ResponseField name="type" type="string">
      Type of barrier (e.g., `"captcha"`, `"2fa"`, `"email-verification"`)
    </ResponseField>

    <ResponseField name="description" type="string">
      Description of the barrier
    </ResponseField>

    <ResponseField name="bypassed" type="boolean">
      Whether the barrier was successfully bypassed
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="authDataPath" type="string">
  Absolute path to the persisted auth-data.json file in the session directory
</ResponseField>

***

## Usage Examples

<CodeGroup>
  ```typescript Basic Authentication theme={null}
  import { runAuthenticationAgent } from '@pensar/apex/api/authentication';
  import { createSession } from '@pensar/apex/session';

  // Create session with credentials
  const session = await createSession({
    name: 'Auth Test',
    targets: ['https://app.example.com'],
    config: {
      authCredentials: {
        username: 'testuser',
        password: 'testpass',
        loginUrl: 'https://app.example.com/login',
      },
    },
  });

  // Run authentication
  const result = await runAuthenticationAgent({
    target: 'https://app.example.com',
    model: 'claude-sonnet-4-20250514',
    session,
  });

  if (result.success) {
    console.log('Authenticated successfully!');
    console.log(`Strategy: ${result.strategy}`);
    
    // Use exported credentials in subsequent requests
    const response = await fetch('https://app.example.com/api/user', {
      headers: {
        Cookie: result.exportedCookies,
        ...result.exportedHeaders,
      },
    });
  }
  ```

  ```typescript OAuth Authentication theme={null}
  import { runAuthenticationAgent } from '@pensar/apex/api/authentication';
  import { createSession } from '@pensar/apex/session';

  const session = await createSession({
    name: 'OAuth Test',
    targets: ['https://api.example.com'],
    config: {
      authCredentials: {
        username: 'testuser@example.com',
        password: 'testpass',
        loginUrl: 'https://accounts.example.com/oauth/authorize',
      },
    },
  });

  const result = await runAuthenticationAgent({
    target: 'https://api.example.com',
    model: 'claude-sonnet-4-20250514',
    session,
    authHints: {
      authScheme: 'oauth2',
      browserRequired: true,
    },
  });

  if (result.success) {
    // OAuth token is in exportedHeaders
    console.log(`Access Token: ${result.exportedHeaders.Authorization}`);
  }
  ```

  ```typescript With Progress Monitoring theme={null}
  import { runAuthenticationAgent } from '@pensar/apex/api/authentication';
  import { createSession } from '@pensar/apex/session';

  const session = await createSession({
    name: 'Monitored Auth',
    targets: ['https://app.example.com'],
    config: {
      authCredentials: {
        username: 'admin',
        password: 'adminpass',
        loginUrl: 'https://app.example.com/admin/login',
      },
    },
  });

  const result = await runAuthenticationAgent({
    target: 'https://app.example.com',
    model: 'claude-sonnet-4-20250514',
    session,
    callbacks: {
      onTextDelta: (d) => process.stdout.write(d.text),
      
      onToolCall: (d) => {
        console.log(`\n→ ${d.toolName}`);
        // Track authentication steps
        if (d.toolName === 'browser_navigate') {
          console.log(`  Navigating to: ${d.args.url}`);
        } else if (d.toolName === 'browser_fill') {
          console.log(`  Filling field: ${d.args.selector}`);
        }
      },
      
      onToolResult: (d) => {
        console.log(`✓ ${d.toolName}`);
      },
    },
  });

  console.log(`\nAuthentication ${result.success ? 'succeeded' : 'failed'}`);
  console.log(result.summary);
  ```

  ```typescript API Key Authentication theme={null}
  import { runAuthenticationAgent } from '@pensar/apex/api/authentication';
  import { createSession } from '@pensar/apex/session';

  const session = await createSession({
    name: 'API Key Auth',
    targets: ['https://api.example.com'],
    config: {
      authCredentials: {
        apiKey: 'sk_live_abc123...',
        loginUrl: 'https://api.example.com/v1',
      },
    },
  });

  const result = await runAuthenticationAgent({
    target: 'https://api.example.com',
    model: 'claude-sonnet-4-20250514',
    session,
    authHints: {
      authScheme: 'api-key',
      protectedEndpoints: [
        'https://api.example.com/v1/users',
        'https://api.example.com/v1/orders',
      ],
    },
  });

  if (result.success) {
    console.log('API key validated');
    console.log(`Headers: ${JSON.stringify(result.exportedHeaders)}`);
  }
  ```

  ```typescript Multi-Step Authentication theme={null}
  import { runAuthenticationAgent } from '@pensar/apex/api/authentication';
  import { createSession } from '@pensar/apex/session';

  // For 2FA/MFA flows with email verification
  const session = await createSession({
    name: '2FA Test',
    targets: ['https://secure.example.com'],
    config: {
      authCredentials: {
        username: 'user@example.com',
        password: 'password123',
        loginUrl: 'https://secure.example.com/login',
      },
      // Configure email access for 2FA code retrieval
      emailInboxes: [
        {
          email: 'user@example.com',
          provider: 'gmail',
          credentials: { /* ... */ },
        },
      ],
    },
  });

  const result = await runAuthenticationAgent({
    target: 'https://secure.example.com',
    model: 'claude-sonnet-4-20250514',
    session,
    authHints: {
      browserRequired: true,
    },
  });

  if (result.authBarrier) {
    console.log(`Encountered barrier: ${result.authBarrier.type}`);
    console.log(`Bypassed: ${result.authBarrier.bypassed}`);
  }
  ```
</CodeGroup>

***

## Credential Management

### Automatic Credential Provisioning

When you create a session with `authCredentials`, a `CredentialManager` is automatically created:

```typescript theme={null}
const session = await createSession({
  name: 'My Session',
  targets: ['https://example.com'],
  config: {
    authCredentials: {
      username: 'user',
      password: 'pass',
      loginUrl: 'https://example.com/login',
    },
  },
});

// session.credentialManager is now available
```

The `CredentialManager`:

* Stores secrets securely in memory
* Never exposes raw secrets in AI prompts
* Provides credential IDs for safe reference
* Resolves secrets only at tool execution time

### Supported Credential Types

* **Username/Password**: Traditional form-based authentication
* **API Keys**: Bearer tokens, API keys
* **OAuth Tokens**: Access tokens, refresh tokens
* **Session Cookies**: Pre-authenticated session cookies
* **Custom Fields**: Any additional auth fields

***

## Authentication Strategies

The agent automatically detects and handles various authentication mechanisms:

### Form-Based Authentication

* Detects username/password fields
* Handles CSRF tokens
* Manages session cookies
* Follows redirects

### OAuth 2.0

* Handles authorization flow
* Manages token exchange
* Exports access tokens

### API Key/Bearer Token

* Validates API key format
* Tests protected endpoints
* Exports authorization headers

### Session-Based

* Imports existing cookies
* Validates session state
* Exports refreshed session

***

## Related APIs

<CardGroup cols={2}>
  <Card title="Blackbox Pentest" icon="shield-halved" href="/api/blackbox-pentest">
    Full pentest with automatic auth
  </Card>

  <Card title="Targeted Pentest" icon="bullseye" href="/api/targeted-pentest">
    Test authenticated endpoints
  </Card>

  <Card title="Attack Surface" icon="radar" href="/api/attack-surface">
    Map authenticated attack surface
  </Card>
</CardGroup>
