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

# Authentication overview

> Learn about PocketBase authentication system and available methods

PocketBase provides a flexible authentication system for auth collections. You can enable multiple authentication methods and configure them based on your application needs.

## Authentication methods

PocketBase supports several authentication methods that can be enabled independently:

<CardGroup cols={2}>
  <Card title="Email/Password" icon="envelope" href="/auth/email-password">
    Traditional authentication using email and password with customizable identity fields
  </Card>

  <Card title="OAuth2" icon="globe" href="/auth/oauth2">
    Social login with 15+ providers including Google, GitHub, and Facebook
  </Card>

  <Card title="OTP" icon="key" href="/auth/otp">
    One-time password authentication via email for passwordless login
  </Card>

  <Card title="MFA" icon="shield-halved" href="/auth/mfa">
    Multi-factor authentication requiring two different auth methods
  </Card>
</CardGroup>

## Auth collection configuration

Every auth collection has an `authRule` that you can use to specify additional constraints applied after record authentication and before returning the auth token response to the client.

```go theme={null}
// Example: Allow only verified users to authenticate
collection.AuthRule = types.Pointer("verified = true")

// Example: Allow any auth record to authenticate
collection.AuthRule = types.Pointer("")

// Example: Disallow authentication altogether
collection.AuthRule = nil
```

<Note>
  The `authRule` check happens in `RecordAuthResponse` after the initial authentication succeeds but before the token is issued.
</Note>

## Authentication flow

The typical authentication flow in PocketBase follows these steps:

<Steps>
  <Step title="Retrieve auth methods">
    Client calls `GET /api/collections/{collection}/auth-methods` to discover available authentication methods.
  </Step>

  <Step title="Authenticate user">
    Client submits credentials using one of the enabled methods (password, OAuth2, or OTP).
  </Step>

  <Step title="Auth rule validation">
    PocketBase validates the record against the collection's `authRule` if configured.
  </Step>

  <Step title="MFA check (optional)">
    If MFA is enabled and required for the user, PocketBase returns an `mfaId` instead of the auth token.
  </Step>

  <Step title="Second factor (MFA)">
    If MFA is required, client authenticates again using a different method with the `mfaId` parameter.
  </Step>

  <Step title="Receive token">
    PocketBase returns the auth token and record data upon successful authentication.
  </Step>
</Steps>

## Auth response structure

Successful authentication returns a JSON response with the following structure:

```json theme={null}
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "record": {
    "id": "RECORD_ID",
    "collectionId": "_pb_users_auth_",
    "collectionName": "users",
    "email": "test@example.com",
    "emailVisibility": false,
    "verified": true,
    "created": "2024-01-01 00:00:00.000Z",
    "updated": "2024-01-01 00:00:00.000Z"
  },
  "meta": {}
}
```

<Info>
  The `meta` field contains additional provider-specific information (e.g., OAuth2 user data).
</Info>

## Token configuration

Auth collections have several token configurations that control the lifetime and security of various tokens:

| Token Type           | Purpose                     | Default Duration   |
| -------------------- | --------------------------- | ------------------ |
| `authToken`          | Main authentication token   | 7 days (604800s)   |
| `passwordResetToken` | Password reset verification | 30 minutes (1800s) |
| `emailChangeToken`   | Email change verification   | 30 minutes (1800s) |
| `verificationToken`  | Email verification          | 3 days (259200s)   |
| `fileToken`          | Protected file access       | 3 minutes (180s)   |

Each token configuration includes:

* **Secret**: Random 50-character string for signing tokens (minimum 30 characters)
* **Duration**: Token validity period in seconds (minimum 10s, maximum \~3 years)

```go theme={null}
type TokenConfig struct {
    Secret   string `json:"secret,omitempty"`
    Duration int64  `json:"duration"` // in seconds
}
```

## Auth alerts

PocketBase can send email alerts when users authenticate from new devices or locations. This feature helps users detect unauthorized access to their accounts.

```go theme={null}
type AuthAlertConfig struct {
    Enabled       bool          `json:"enabled"`
    EmailTemplate EmailTemplate `json:"emailTemplate"`
}
```

<Note>
  Auth alerts are only sent after the first successful login. The system tracks up to 5 authentication origins per user based on IP address and user agent fingerprints.
</Note>

## Security features

### Rate limiting

All authentication endpoints include rate limiting to prevent brute force attacks:

```go theme={null}
// Example from record_auth.go
sub.POST("/auth-with-password", recordAuthWithPassword).Bind(
    collectionPathRateLimit("", "authWithPassword", "auth"),
)
```

### Token key rotation

Every auth record has a `tokenKey` field that is used to sign auth tokens. When the password changes, the token key is automatically refreshed, invalidating all existing sessions:

```go theme={null}
// From record_model_auth.go
func (m *Record) RefreshTokenKey() {
    m.Set(FieldNameTokenKey+autogenerateModifier, "")
}
```

### Email verification

Auth records track email verification status. OAuth2 and OTP authentication can automatically verify emails:

```go theme={null}
func (m *Record) Verified() bool {
    return m.GetBool(FieldNameVerified)
}

func (m *Record) SetVerified(verified bool) {
    m.Set(FieldNameVerified, verified)
}
```

## Manage rule

The `manageRule` gives admin-like permissions for auth records, allowing operations like:

* Changing passwords without requiring the old password
* Directly updating the verified state
* Modifying the email without confirmation
* Ignoring email visibility settings

<Warning>
  The manage rule is executed in addition to the Create and Update API rules. Be careful when setting this rule as it grants elevated permissions.
</Warning>

## Common endpoints

All auth collections automatically get the following endpoints:

| Method | Endpoint                                               | Description                 |
| ------ | ------------------------------------------------------ | --------------------------- |
| GET    | `/api/collections/{collection}/auth-methods`           | List available auth methods |
| POST   | `/api/collections/{collection}/auth-refresh`           | Refresh auth token          |
| POST   | `/api/collections/{collection}/auth-with-password`     | Authenticate with password  |
| POST   | `/api/collections/{collection}/auth-with-oauth2`       | Authenticate with OAuth2    |
| POST   | `/api/collections/{collection}/request-otp`            | Request OTP code            |
| POST   | `/api/collections/{collection}/auth-with-otp`          | Authenticate with OTP       |
| POST   | `/api/collections/{collection}/request-password-reset` | Request password reset      |
| POST   | `/api/collections/{collection}/confirm-password-reset` | Confirm password reset      |
| POST   | `/api/collections/{collection}/request-verification`   | Request email verification  |
| POST   | `/api/collections/{collection}/confirm-verification`   | Confirm email verification  |
| POST   | `/api/collections/{collection}/request-email-change`   | Request email change        |
| POST   | `/api/collections/{collection}/confirm-email-change`   | Confirm email change        |

## Next steps

<CardGroup cols={2}>
  <Card title="Email/Password auth" icon="envelope" href="/auth/email-password">
    Configure traditional password authentication
  </Card>

  <Card title="OAuth2 providers" icon="globe" href="/auth/oauth2">
    Set up social login providers
  </Card>

  <Card title="API rules" icon="shield" href="/auth/api-rules">
    Learn about access control
  </Card>

  <Card title="MFA setup" icon="shield-halved" href="/auth/mfa">
    Enable multi-factor authentication
  </Card>
</CardGroup>
