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
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)
Auth collection IDs must be unique across all auth collections to prevent authentication conflicts.
Authentication methods
PocketBase supports multiple authentication strategies:
Password authentication
The traditional username/password authentication:
// 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:
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:
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:
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:
// 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
Auth rules are evaluated after successful password/OAuth2 verification and before issuing the auth token.
Manage rules
Manage rules grant admin-like permissions for auth operations:
// 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:
collection . AuthToken = core . TokenConfig {
Secret : "auto-generated" ,
Duration : 604800 , // 7 days in seconds
}
Password reset token
For password recovery:
collection . PasswordResetToken = core . TokenConfig {
Secret : "auto-generated" ,
Duration : 1800 , // 30 minutes
}
Email change token
For confirming email address changes:
collection . EmailChangeToken = core . TokenConfig {
Secret : "auto-generated" ,
Duration : 1800 , // 30 minutes
}
Verification token
For email verification:
collection . VerificationToken = core . TokenConfig {
Secret : "auto-generated" ,
Duration : 259200 , // 3 days
}
File token
For accessing protected files:
collection . FileToken = core . TokenConfig {
Secret : "auto-generated" ,
Duration : 180 , // 3 minutes
}
Token secrets are automatically generated and rotated when needed. Never expose these secrets publicly.
Working with auth records
Creating users
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
// 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 ()
Setting a new password automatically refreshes the tokenKey, invalidating all existing auth tokens for that user.
Email verification
// Mark user as verified
record . SetVerified ( true )
app . Save ( record )
// Check verification status
if record . Verified () {
// User is verified
}
Token key management
// 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:
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
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
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
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:
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:
// @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 for more details.
Security best practices
Use strong password requirements
Configure minimum password length and complexity in your password field settings. The default minimum is 8 characters.
Enable email verification
Require email verification before allowing full access to your application. Use auth rules like verified = true.
Protect authentication endpoints from brute force attacks by implementing rate limiting in your hooks.
Always use HTTPS in production to protect authentication tokens and credentials during transmission.
Rotate token secrets carefully
Changing token secrets (like AuthToken.Secret) invalidates all existing tokens. Plan token rotation during low-traffic periods.
Enable MFA for sensitive operations
Consider requiring MFA for users with elevated privileges or access to sensitive data.
Enable auth alerts to help users detect unauthorized access attempts.
When using custom identity fields (like username), ensure they have unique constraints to prevent impersonation.