Kritim Yantra
Mar 27, 2025
Authentication (who you are) and Authorization (what you can do) are essential for securing web applications. Laravel makes it incredibly easy to implement both.
In this guide, we’ll cover:
✅ Authentication Setup (Login, Register, Password Reset)
✅ Authorization (Gates, Policies, Middleware)
✅ Role-Based Access Control (RBAC)
✅ Best Practices for Security
Let’s get started!
Authentication verifies who a user is. Examples:
Laravel provides built-in scaffolding for authentication.
composer create-project laravel/laravel laravel-auth
cd laravel-auth
Configure .env
with your database:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_auth
DB_USERNAME=root
DB_PASSWORD=
Run migrations:
php artisan migrate
Laravel Breeze provides login, registration, and password reset out of the box.
composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate
Now visit:
🔗 http://localhost:8000/register (Registration)
🔗 http://localhost:8000/login (Login)
✅ You now have a fully working auth system!
Laravel uses:
Example: Custom login logic in LoginController
:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::attempt($credentials)) {
return redirect('/dashboard'); // Login success
}
return back()->withErrors(['email' => 'Invalid credentials']); // Login failed
}
@if (Auth::check())
<p>Welcome, {{ Auth::user()->name }}!</p>
@endif
Auth::logout();
return redirect('/');
Authorization controls what a user can do. Examples:
Laravel provides Gates and Policies for authorization.
Gates are Closure-based checks (good for simple rules).
App\Providers\AuthServiceProvider
)use Illuminate\Support\Facades\Gate;
public function boot()
{
Gate::define('access-admin', function ($user) {
return $user->is_admin; // Checks if user is admin
});
}
public function adminDashboard()
{
if (Gate::allows('access-admin')) {
return view('admin.dashboard');
}
abort(403, 'Unauthorized!');
}
Route::get('/admin', function () {
// Only admins can access
})->middleware('can:access-admin');
Policies are class-based and useful for model-specific permissions.
php artisan make:policy PostPolicy --model=Post
PostPolicy.php
public function update(User $user, Post $post)
{
return $user->id === $post->user_id; // Only post owner can edit
}
public function edit(Post $post)
{
$this->authorize('update', $post); // Checks policy
return view('posts.edit', compact('post'));
}
Route::put('/posts/{post}', [PostController::class, 'update'])
->middleware('can:update,post');
For complex apps, use roles (Admin, Editor, User).
role
Column to Usersphp artisan make:migration add_role_to_users_table --table=users
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->enum('role', ['admin', 'editor', 'user'])->default('user');
});
}
Run migration:
php artisan migrate
php artisan make:middleware CheckAdmin
Edit app/Http/Middleware/CheckAdmin.php
:
public function handle($request, Closure $next)
{
if (Auth::check() && Auth::user()->role === 'admin') {
return $next($request);
}
abort(403, 'Access Denied!');
}
Route::get('/admin', function () {
return view('admin.dashboard');
})->middleware('auth', 'checkadmin');
✔ Use HTTPS to prevent data interception.
✔ Hash passwords (Laravel does this automatically).
✔ Limit login attempts (use ThrottleRequests
middleware).
✔ Sanitize user input to prevent SQL injection.
✔ Use @csrf
in forms to prevent CSRF attacks.
✅ Authentication = Who are you? (Login/Register)
✅ Authorization = What can you do? (Gates/Policies)
✅ RBAC = Control access via roles (Admin, User)
🚀 Now go ahead and secure your Laravel app!
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google