Authentication and Authorization

Authentication

Laravel provides built-in authentication and session services via the Auth and Session facades. These handle cookie-based authentication, verify user credentials, store authentication data in sessions, and issue session cookies automatically.

  • Modules
    • Guards
      • User authentication for each request
    • Providers
      • define how users are retrieved from the database.
  • Configuration
    • config/auth.php

Configuration

This config defines Laravel's authentication settings. The default guard (web) uses session-based authentication, and the user provider relies on Eloquent with the User model.

config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],

Database Preparation

This sets up the database connection for Laravel using MySQL. The migrate command applies database migrations to create the necessary tables.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=onlineShop
DB_USERNAME=laravel
DB_PASSWORD=laravel
php artisan migrate

It creates tables in the database (users)


Register

This is a simple Laravel registration form with CSRF protection. It includes fields for name, email, password, and password confirmation, displaying validation error messages if input is invalid.

in view
<h1>Register</h1>
<form action="/register" methode="post" >
@csrf
<label>Name</label>
<input type="text" name="name" value="{{old('name')}}" />
@error('name')
{{$message}}
@enderror
<br/>
<label>Email</label>
<input type="text" name="email" value="{{old('email')}}" />
@error('email')
{{$message}}
@enderror
<br/>
<label>Password</label>
<input type="password" name="password" />
@error('password')
{{$message}}
@enderror
<br/>
<label>Repeat password</label>
<input type="password" name="password_confirmation" />
@error('password_confirmation')
{{$message}}
@enderror
<br/>
<input type="submit" value="register" />
</form>
in controller
public function register(Request $request)
{

$validate = $request->validate(

[
'name' => 'required|max:255',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:8|confirmed',
]
);
$user= User::create([
'name' => $request->input('name'),
'email'=> $request->input('email'),
'password' => Hash::make($request->input('password'))
]);

return redirect('/');

}

This controller method validates the registration form, creates a new user with a hashed password, and then redirects to the homepage.


Login

To use Laravel's authentication services, import the Auth facade. The attempt method handles login authentication. If successful, regenerate the session to prevent session fixation.

use Illuminate\Support\Facades\Auth;
in controller
public function login(Request $request)
{
$credentials = $request -> only('email', 'password');

if (Auth::attempt( $credentials))
{
$request -> session()->regenerate();

return view('welcome')
}

return back()->withErrors(['email' => 'Incorrect email or password!']);

}
in view
<h1>Login</h1>
@error('error')
{{$message}}
@enderror
<br/>
<form action="/login" methode="post" >
@csrf
<label>Email</label>
<input type="text" name="email" /> <br/>
<label>Password</label>
<input type="password" name="password" /> <br/>
<input type="submit" value="Login"
</form>

This is a Laravel login form with CSRF protection. It includes fields for email and password and displays error messages if authentication fails.


Logout

Use the logout method from the Auth facade to log users out by removing authentication data from the session. Additionally, invalidate the session, regenerate the CSRF token, and redirect the user to the root.

public function logout(Request $request)
{
Auth::logout();

$request -> session()->invalidate();

$request -> session()->regenerateToken();

return redirect('/');

}

Helper Methods

Get the logged-in user

After a user registers and logs in, you can access the authenticated user using the user method of the Auth facade while handling a request.

// Retrieve the currently authenticated user...
$user = Auth::user();

// Retrieve the currently authenticated user's ID...
< $id = Auth::id();
Is the user logged in?

To check if a user is authenticated, use the check method on the Auth facade. It returns true if the user is logged in.

if( Auth::check()) {
//User is logged in
}
Protect routes
Route::get('/flights',function(){
Only logged-in users can access this route.
})->middleware('auth');
Redirect user if not logged in

If the auth middleware detects an unauthenticated user, it redirects them to the login route.

app/Http/Middleware/Authenticate.php
protected function redirectTo(Request $request): string
{
return route('login');
}

Authorization

  • Modules
    • Gates
      • Permissions for actions
    • Policies
      • Permissions for model classes

Update the database

  • Add a new attribute to the user named "role"
  • Update the User model
protected $fillable = [
'name' ,
'email',
'password',
'role',
];

Define Gates

Gates are closures that check if a user is authorized for an action. They are defined in the boot method of AppServiceProvider using the Gate facade and receive a user instance as the first argument.

app/Providers/AuthServiceProvider.php
public function boot(): void
{
Gate::define('isAdmin', function ($user) {
return $user->role == 'ADMIN';
});

Gate::define('isUser', function ($user) {
return $user->role == 'USER';
});
}

Check gates

To authorize an action with gates, use the allows or denies methods from the Gate facade. Laravel automatically passes the authenticated user, so you don’t need to include it manually. These methods are typically used in controllers before executing restricted actions.

In Controller
public function index(Request $request)
{
if (Gate::allows('isAdmin))
return view('welcome');
else
return redirect('/);
}
Via Middleware

Laravel provides middleware to authorize actions before the request reaches routes or controllers. The Illuminate\Auth\Middleware\Authorize middleware can be attached to a route using the can middleware alias, which is automatically registered by Laravel.

Route::get('/welcome', [userController::class, 'index'])->middleware('can:isAdmin');

Helper Methods

Show or hide elements in the view based on the user's role

@can('isAdmin')
Admin
@else
everyone
@endcan

@canany(['isAdmin','isUser'])
everyone
@endcanany