> ## 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

> User authentication and authorization in PocketBase

PocketBase provides a comprehensive authentication system with support for multiple authentication methods, token management, and fine-grained access control through API rules.

## Auth collections

Authentication in PocketBase is built around auth collections - specialized collections with built-in authentication features.

### Creating auth collections

```go theme={null}
collection := core.NewAuthCollection("users")

// Add custom fields
collection.Fields.Add(
    &core.TextField{
        Name:     "name",
        Required: true,
    },
    &core.TextField{
        Name:   "username",
        Unique: true,
    },
)

app.Save(collection)
```

### Built-in auth fields

Every auth collection automatically includes:

* **id** - Unique identifier (15 chars, unique across all auth collections)
* **email** - Email address with unique constraint
* **emailVisibility** - Controls public visibility of email
* **verified** - Email verification status
* **password** - Bcrypt-hashed password (never returned in API responses)
* **tokenKey** - Session token secret (never returned in API responses)

<Warning>
  Auth collection IDs must be unique across **all** auth collections to prevent authentication conflicts.
</Warning>

## Authentication methods

PocketBase supports multiple authentication strategies:

### Password authentication

The traditional username/password authentication:

```go theme={null}
// Configure in collection options
collection.PasswordAuth = core.PasswordAuthConfig{
    Enabled:        true,
    IdentityFields: []string{"email", "username"},
}
```

**Identity fields** determine which fields can be used for login. Users can authenticate with any configured identity field.

### OAuth2 authentication

Support for third-party OAuth2 providers:

```go theme={null}
collection.OAuth2 = core.OAuth2Config{
    Enabled: true,
    Providers: []core.OAuth2ProviderConfig{
        {
            Name:         "google",
            ClientId:     "your-client-id",
            ClientSecret: "your-client-secret",
        },
    },
    MappedFields: core.OAuth2MappedFields{
        Id:        "oauth_id",
        Name:      "name",
        Username:  "username",
        AvatarURL: "avatar",
    },
}
```

**Supported providers:**

* Google
* Facebook
* GitHub
* GitLab
* Discord
* Twitter
* Microsoft
* Spotify
* Kakao
* And more...

### One-time password (OTP)

Passwordless authentication via email:

```go theme={null}
collection.OTP = core.OTPConfig{
    Enabled:       true,
    Duration:      180,  // 3 minutes
    Length:        8,    // 8-digit code
    EmailTemplate: core.EmailTemplate{
        Subject: "Your login code",
        Body:    "Your code is: {OTP}",
    },
}
```

Users receive a one-time code via email that they use to authenticate.

### Multi-factor authentication (MFA)

Add an extra layer of security with TOTP-based MFA:

```go theme={null}
collection.MFA = core.MFAConfig{
    Enabled:  true,
    Duration: 1800,  // 30 minutes
}
```

Users can enable MFA on their accounts and must provide a time-based code after password authentication.

## Auth rules

Auth rules provide additional constraints beyond password/OAuth2 verification:

```go theme={null}
// Only allow verified users to authenticate
collection.AuthRule = types.Pointer("verified = true")

// Only allow users with specific role
collection.AuthRule = types.Pointer("role = 'member'")

// Allow anyone (default)
collection.AuthRule = types.Pointer("")

// Disable authentication entirely
collection.AuthRule = nil
```

<Note>
  Auth rules are evaluated **after** successful password/OAuth2 verification and **before** issuing the auth token.
</Note>

## Manage rules

Manage rules grant admin-like permissions for auth operations:

```go theme={null}
// Allow users to update their own profile without old password
collection.ManageRule = types.Pointer("@request.auth.id = id")

// Allow admins to manage any user
collection.ManageRule = types.Pointer("@request.auth.role = 'admin'")
```

With manage rule access, users can:

* Change password without providing the old one
* Update email without verification
* Modify the `verified` field directly
* Update `emailVisibility` and other protected fields

## Token configuration

Auth collections use multiple token types for different purposes:

### Auth token

Issued after successful authentication:

```go theme={null}
collection.AuthToken = core.TokenConfig{
    Secret:   "auto-generated",
    Duration: 604800,  // 7 days in seconds
}
```

### Password reset token

For password recovery:

```go theme={null}
collection.PasswordResetToken = core.TokenConfig{
    Secret:   "auto-generated",
    Duration: 1800,  // 30 minutes
}
```

### Email change token

For confirming email address changes:

```go theme={null}
collection.EmailChangeToken = core.TokenConfig{
    Secret:   "auto-generated",
    Duration: 1800,  // 30 minutes
}
```

### Verification token

For email verification:

```go theme={null}
collection.VerificationToken = core.TokenConfig{
    Secret:   "auto-generated",
    Duration: 259200,  // 3 days
}
```

### File token

For accessing protected files:

```go theme={null}
collection.FileToken = core.TokenConfig{
    Secret:   "auto-generated",
    Duration: 180,  // 3 minutes
}
```

<Info>
  Token secrets are automatically generated and rotated when needed. Never expose these secrets publicly.
</Info>

## Working with auth records

### Creating users

```go theme={null}
collection, _ := app.FindCollectionByNameOrId("users")
record := core.NewRecord(collection)

record.SetEmail("user@example.com")
record.SetPassword("securePassword123")
record.Set("name", "John Doe")
record.SetVerified(false)

if err := app.Save(record); err != nil {
    return err
}
```

### Password management

```go theme={null}
// Set password (automatically hashed)
record.SetPassword("newPassword123")

// Validate password
if record.ValidatePassword("userInputPassword") {
    // Password is correct
}

// Generate random password (for OAuth2/OTP users)
randomPassword := record.SetRandomPassword()
```

<Warning>
  Setting a new password automatically refreshes the `tokenKey`, invalidating all existing auth tokens for that user.
</Warning>

### Email verification

```go theme={null}
// Mark user as verified
record.SetVerified(true)
app.Save(record)

// Check verification status
if record.Verified() {
    // User is verified
}
```

### Token key management

```go theme={null}
// Get current token key
tokenKey := record.TokenKey()

// Refresh token key (invalidates all sessions)
record.RefreshTokenKey()
app.Save(record)
```

## Auth alerts

Notify users of new login attempts:

```go theme={null}
collection.AuthAlert = core.AuthAlertConfig{
    Enabled: true,
    EmailTemplate: core.EmailTemplate{
        Subject: "New login detected",
        Body:    "New login from {IP} on {Timestamp}",
    },
}
```

Users receive an email when they log in from a new device or location.

## Email templates

Customize authentication emails:

### Verification email

```go theme={null}
collection.VerificationTemplate = core.EmailTemplate{
    Subject: "Verify your email",
    Body: `
        <p>Hello,</p>
        <p>Click the link below to verify your email:</p>
        <a href="{APP_URL}/_/#/auth/confirm-verification/{TOKEN}">
            Verify Email
        </a>
    `,
}
```

### Password reset email

```go theme={null}
collection.ResetPasswordTemplate = core.EmailTemplate{
    Subject: "Reset your password",
    Body: `
        <p>Click the link below to reset your password:</p>
        <a href="{APP_URL}/_/#/auth/confirm-password-reset/{TOKEN}">
            Reset Password
        </a>
    `,
}
```

### Email change confirmation

```go theme={null}
collection.ConfirmEmailChangeTemplate = core.EmailTemplate{
    Subject: "Confirm email change",
    Body: `
        <p>Click the link below to confirm your new email:</p>
        <a href="{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}">
            Confirm Email
        </a>
    `,
}
```

**Available template variables:**

* `{APP_URL}` - Your application URL
* `{APP_NAME}` - Your application name
* `{TOKEN}` - The verification/reset token
* `{ACTION_URL}` - Pre-built action URL

## Authentication in API requests

### Request context

Auth records are available in the request context:

```go theme={null}
app.OnRecordCreate().Bind(&hook.Handler[*core.RecordEvent]{
    Func: func(e *core.RecordEvent) error {
        // Get authenticated user
        authRecord := e.Auth
        
        if authRecord != nil {
            // User is authenticated
            userId := authRecord.Id
            userEmail := authRecord.Email()
        }
        
        return e.Next()
    },
})
```

### API rules context

Access auth data in API rules:

```go theme={null}
// @request.auth.* - The authenticated user record
collection.CreateRule = types.Pointer("@request.auth.id != ''")
collection.UpdateRule = types.Pointer("@request.auth.id = author")
collection.DeleteRule = types.Pointer(
    "@request.auth.id = author || @request.auth.role = 'admin'",
)
```

See [API Rules](/concepts/api-rules) for more details.

## Security best practices

<AccordionGroup>
  <Accordion title="Use strong password requirements">
    Configure minimum password length and complexity in your password field settings. The default minimum is 8 characters.
  </Accordion>

  <Accordion title="Enable email verification">
    Require email verification before allowing full access to your application. Use auth rules like `verified = true`.
  </Accordion>

  <Accordion title="Implement rate limiting">
    Protect authentication endpoints from brute force attacks by implementing rate limiting in your hooks.
  </Accordion>

  <Accordion title="Use HTTPS in production">
    Always use HTTPS in production to protect authentication tokens and credentials during transmission.
  </Accordion>

  <Accordion title="Rotate token secrets carefully">
    Changing token secrets (like `AuthToken.Secret`) invalidates all existing tokens. Plan token rotation during low-traffic periods.
  </Accordion>

  <Accordion title="Enable MFA for sensitive operations">
    Consider requiring MFA for users with elevated privileges or access to sensitive data.
  </Accordion>

  <Accordion title="Monitor auth alerts">
    Enable auth alerts to help users detect unauthorized access attempts.
  </Accordion>

  <Accordion title="Validate identity fields">
    When using custom identity fields (like username), ensure they have unique constraints to prevent impersonation.
  </Accordion>
</AccordionGroup>
