When to Use OAuth 2.0
- User-centric applications — Users access their own Google Sheets
- Multi-tenant applications — Different users access different spreadsheets
- Personal data access — Reading/writing user’s personal Google account data
- Web applications — Apps where user interaction is available
Prerequisites
- Google Cloud Console project
- Google Sheets API and Google Drive API enabled
- Laravel Socialite package (recommended)
Setup Steps
1
Configure Google Cloud Console
- Go to Google Cloud Console
- Select your project or create a new one
- Navigate to APIs & Services > Library
- Enable:
- Google Sheets API
- Google Drive API
2
Create OAuth 2.0 Credentials
- Go to APIs & Services > Credentials
- Click Create Credentials > OAuth client ID
- Configure OAuth consent screen (first time only):
- Choose External for public apps
- Fill required fields (app name, support email, developer contact)
- Add scopes:
https://www.googleapis.com/auth/spreadsheetsandhttps://www.googleapis.com/auth/drive
- Select Web application as application type
- Add Authorized Redirect URIs:
- Development:
http://localhost:8000/auth/google/callback - Production:
https://yourdomain.com/auth/google/callback
- Development:
- Click Create
- Copy your Client ID and Client Secret
3
Configure Laravel Environment
Add to Update
.env:config/google.php:4
Install Laravel Socialite
config/services.php:5
Implement OAuth Flow
Create an authentication controller:
6
Add Routes
7
Update User Model
Create migration:Update User model:
8
Use Sheets with OAuth
Token Refresh
The package automatically handles token refresh when expired:Middleware
Create middleware to require Google authentication:Security Considerations
1. Token Storage
- Store tokens securely in the database
- Use Laravel’s built-in encryption
- Never expose tokens in client-side code
2. Scope Management
- Only request necessary scopes
- Follow the principle of least privilege
- Clearly explain to users what access you need
3. Error Handling
- Handle expired tokens gracefully
- Provide clear re-authentication flows
- Log authentication errors for monitoring
Troubleshooting
Common Errors
“redirect_uri_mismatch” error- Verify redirect URI in Google Console matches exactly
- Check for http vs https differences
- Verify trailing slashes match
- Token has expired and refresh failed
- Redirect user to re-authenticate
- Check if refresh token is available
- User denied permission
- Handle gracefully with appropriate messaging
- Provide option to retry authentication