Authentication vs Authorization
Understanding the difference between authentication and authorization is crucial for implementing secure applications:
- Authentication: Verifying who the user is (login)
- Authorization: Determining what the user can do (permissions)
Laravel Sanctum Implementation
Laravel Sanctum provides a simple authentication system for SPAs and mobile applications:
// Install Sanctum
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
// Create token for user
$user = User::find(1);
$token = $user->createToken('API Token')->plainTextToken;
// Protect routes
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
JWT Implementation
JSON Web Tokens provide stateless authentication:
// Generate JWT token
$payload = [
'user_id' => $user->id,
'exp' => time() + (60 * 60), // 1 hour expiry
];
$jwt = JWT::encode($payload, config('app.key'), 'HS256');
// Verify JWT token
try {
$decoded = JWT::decode($token, new Key(config('app.key'), 'HS256'));
$user = User::find($decoded->user_id);
} catch (Exception $e) {
// Invalid token
}
Role-Based Access Control (RBAC)
Implement roles and permissions system:
// Database structure
roles: id, name
permissions: id, name
role_permissions: role_id, permission_id
user_roles: user_id, role_id
// Check permissions in Laravel
Gate::define('edit-post', function ($user, $post) {
return $user->hasPermission('edit-posts') || $user->id === $post->user_id;
});
// Use in controllers
if (Gate::allows('edit-post', $post)) {
// User can edit this post
}
Security Best Practices
- Password Hashing: Always hash passwords with bcrypt
- CSRF Protection: Use CSRF tokens for forms
- Rate Limiting: Prevent brute force attacks
- HTTPS Only: Never transmit auth data over HTTP
- Token Expiry: Implement reasonable token lifetimes
Frontend Integration
// Vue.js authentication example
const login = async (credentials) => {
try {
const response = await axios.post('/api/login', credentials);
const { token, user } = response.data;
// Store token securely
localStorage.setItem('auth_token', token);
// Set default authorization header
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
return { success: true, user };
} catch (error) {
return { success: false, message: error.response.data.message };
}
};
OAuth Integration
Integrate with third-party providers like Google, GitHub, or Facebook:
// Laravel Socialite
composer require laravel/socialite
// Configure providers in config/services.php
'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => 'http://localhost/auth/github/callback',
],
Implementing robust authentication and authorization requires careful planning and attention to security details. Always stay updated with the latest security practices and regularly audit your implementation.