Authentication Setup
Configure authentication providers and security settings for your SAMS instance.
Authentication Setup
SAMS uses Better Auth to provide comprehensive authentication with multiple providers, security features, and session management. This guide covers setting up and configuring authentication.
Overview
SAMS supports multiple authentication methods:
- Password-based login with email/password
- Magic links for passwordless authentication
- OAuth providers (Google, GitHub, etc.)
- Passkeys for WebAuthn authentication
- Two-factor authentication for enhanced security
Basic Configuration
Environment Variables
Set up basic authentication environment variables:
# Required for authentication
NEXTAUTH_SECRET="your-long-random-secret-key"
NEXTAUTH_URL="http://localhost:3000"
# Application URL
NEXT_PUBLIC_APP_URL="http://localhost:3000"Authentication Settings
Configure authentication features in config/index.ts:
// config/index.ts
auth: {
// User registration
enableSignup: true,
// Authentication methods
enableMagicLink: true,
enableSocialLogin: true,
enablePasskeys: true,
enablePasswordLogin: true,
enableTwoFactor: true,
// Redirects
redirectAfterSignIn: "/app",
redirectAfterLogout: "/",
// Session configuration
sessionCookieMaxAge: 60 * 60 * 24 * 30, // 30 days
}OAuth Providers
Google OAuth
-
Create Google OAuth Application:
- Go to Google Cloud Console
- Create a new project or select existing
- Enable Google+ API
- Create OAuth 2.0 credentials
-
Configure Authorized Redirect URIs:
http://localhost:3000/api/auth/callback/google https://yourdomain.com/api/auth/callback/google -
Add Environment Variables:
GOOGLE_CLIENT_ID="your-google-client-id" GOOGLE_CLIENT_SECRET="your-google-client-secret"
GitHub OAuth
-
Create GitHub OAuth App:
- Go to GitHub Settings > Developer settings > OAuth Apps
- Click "New OAuth App"
- Set Authorization callback URL:
http://localhost:3000/api/auth/callback/github
-
Add Environment Variables:
GITHUB_CLIENT_ID="your-github-client-id" GITHUB_CLIENT_SECRET="your-github-client-secret"
Microsoft OAuth
-
Create Azure AD Application:
- Go to Azure Portal
- Register new application
- Set redirect URI:
http://localhost:3000/api/auth/callback/microsoft
-
Add Environment Variables:
MICROSOFT_CLIENT_ID="your-microsoft-client-id" MICROSOFT_CLIENT_SECRET="your-microsoft-client-secret"
Discord OAuth
-
Create Discord Application:
- Go to Discord Developer Portal
- Create new application
- Add redirect URI:
http://localhost:3000/api/auth/callback/discord
-
Add Environment Variables:
DISCORD_CLIENT_ID="your-discord-client-id" DISCORD_CLIENT_SECRET="your-discord-client-secret"
Adding Custom OAuth Providers
You can add custom OAuth providers by extending the Better Auth configuration:
// packages/auth/src/config.ts
import { betterAuth } from "better-auth"
import { customProvider } from "./providers/custom"
export const auth = betterAuth({
// ... existing config
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
// Add your custom provider
customProvider: {
clientId: process.env.CUSTOM_CLIENT_ID!,
clientSecret: process.env.CUSTOM_CLIENT_SECRET!,
},
},
})Magic Link Authentication
Magic links provide passwordless authentication via email.
Email Provider Setup
Choose an email provider for sending magic links:
Resend (Recommended)
RESEND_API_KEY="re_your_resend_api_key"
EMAIL_FROM="noreply@yourdomain.com"Postmark
POSTMARK_API_KEY="your_postmark_api_key"
EMAIL_FROM="noreply@yourdomain.com"SMTP
SMTP_HOST="smtp.yourdomain.com"
SMTP_PORT="587"
SMTP_USER="your_smtp_user"
SMTP_PASS="your_smtp_password"
EMAIL_FROM="noreply@yourdomain.com"Magic Link Configuration
Configure magic link settings:
// packages/auth/src/config.ts
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
sendEmailVerificationOnSignUp: true,
},
magicLink: {
enabled: true,
expiresIn: 300, // 5 minutes
},
})Passkey Authentication
Passkeys provide secure, passwordless authentication using biometrics or device PIN.
Enable Passkeys
// config/index.ts
auth: {
enablePasskeys: true,
// ... other settings
}Passkey Configuration
// packages/auth/src/config.ts
export const auth = betterAuth({
passkey: {
enabled: true,
relyingParty: {
name: "SAMS",
id: "localhost", // or "yourdomain.com" in production
},
},
})Production Setup
For production, ensure your domain is properly configured:
// packages/auth/src/config.ts (production)
passkey: {
enabled: true,
relyingParty: {
name: "Your App Name",
id: "yourdomain.com",
},
}Two-Factor Authentication
Enable 2FA
// config/index.ts
auth: {
enableTwoFactor: true,
// ... other settings
}2FA Configuration
// packages/auth/src/config.ts
export const auth = betterAuth({
twoFactor: {
enabled: true,
issuer: "Your App Name",
},
})Session Management
Session Configuration
Configure session behavior:
// packages/auth/src/config.ts
export const auth = betterAuth({
session: {
cookieCache: {
enabled: true,
maxAge: 60 * 5, // 5 minutes
},
updateAge: 60 * 60 * 24, // 24 hours
expiresIn: 60 * 60 * 24 * 30, // 30 days
},
})Session Security
Configure security settings:
// packages/auth/src/config.ts
export const auth = betterAuth({
advanced: {
crossSubDomainCookies: {
enabled: false,
},
useSecureCookies: process.env.NODE_ENV === "production",
},
})User Roles and Permissions
Organization Roles
SAMS includes built-in organization roles:
- Organization Admin: Full control over organization
- Organization Member: Access to organization resources
Custom Roles
Add custom roles by extending the database schema:
// packages/database/schema.prisma
model Member {
id String @id @default(cuid())
userId String
organizationId String
role MemberRole @default(MEMBER)
// Add custom roles
customRole String?
permissions String[] // JSON array of permissions
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
}
enum MemberRole {
ADMIN
MEMBER
// Add custom roles here
VIEWER
EDITOR
}Permission Checking
Use the permission system in your components:
// Example usage
import { useOrganization } from '@/hooks/use-organization'
export function AdminOnlyComponent() {
const { userRole, hasPermission } = useOrganization()
if (userRole !== 'ADMIN') {
return <div>Access denied</div>
}
return <div>Admin content</div>
}Security Best Practices
Password Security
Configure strong password requirements:
// packages/auth/src/config.ts
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
maxPasswordLength: 128,
requireEmailVerification: true,
},
})Rate Limiting
Implement rate limiting for authentication endpoints:
// packages/auth/src/config.ts
export const auth = betterAuth({
rateLimit: {
enabled: true,
window: 60, // 1 minute
max: 10, // 10 attempts
},
})Account Security
Enable account security features:
// packages/auth/src/config.ts
export const auth = betterAuth({
account: {
accountLinking: {
enabled: true,
trustedProviders: ["google", "github"],
},
deleteUser: {
enabled: true,
sendEmail: true,
},
},
})Testing Authentication
Development Testing
-
Create Test User:
# Use the signup flow or create directly in database pnpm db:studio -
Test OAuth Providers:
- Ensure redirect URIs include localhost:3000
- Test each configured provider
-
Test Magic Links:
- Configure email provider
- Test email delivery
Production Testing
- Update OAuth Redirect URIs to production domain
- Test email delivery in production environment
- Verify SSL certificates for security features
- Test session persistence across browser restarts
Troubleshooting
Common Issues
OAuth Provider Errors:
- Verify client ID and secret are correct
- Check redirect URIs match exactly
- Ensure OAuth application is enabled
Magic Link Issues:
- Verify email provider configuration
- Check spam folders for test emails
- Ensure EMAIL_FROM domain is verified
Session Issues:
- Clear browser cookies and try again
- Verify NEXTAUTH_SECRET is set
- Check session expiration settings
Passkey Issues:
- Ensure HTTPS in production
- Verify domain configuration
- Test on supported browsers/devices
Debug Mode
Enable debug mode for authentication:
# Add to .env.local
DEBUG=better-auth:*
NEXTAUTH_DEBUG=trueMigration from Other Auth Systems
From NextAuth.js
SAMS includes utilities to migrate from NextAuth.js:
- Export existing users from your current database
- Run migration script (included in framework)
- Update session handling in your application
- Test authentication flows
From Custom Auth
- Map user data to SAMS schema
- Migrate session data if needed
- Update authentication middleware
- Test thoroughly before going live
Next: Learn about Database Management to understand the data model and how to extend it.