Laravel Authentication Guards

Marickian
By -
0
Laravel Authentication Guards

Laravel Authentication Guards

Authentication guards in Laravel provide a way to define how users authenticate into the application. Laravel allows multiple guards to support different authentication methods, such as session-based, token-based, or custom-defined guards.

1. Configuring Authentication Defaults

Laravel defines a default authentication guard and password broker in the config/auth.php file. This determines which authentication method is used by default.

'defaults' => [
    'guard' => env('AUTH_GUARD', 'web'),
    'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],

You can modify these settings based on your authentication needs.

2. Defining Authentication Guards

You can configure multiple authentication guards. Each guard has a driver (such as session, token, or custom-based authentication) and a provider that retrieves user data.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    'custom' => [
        'driver' => 'custom-auth',
        'provider' => 'custom_users',
    ]
],

Laravel provides a "session" guard by default, but you can define custom authentication drivers.

3. User Providers

Providers define how users are retrieved from the database or another storage system.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
    'custom_users' => [
        'driver' => 'custom-provider',
        'model' => App\Models\CustomUser::class,
    ]
],

The "eloquent" driver is used for retrieving users via Eloquent models, while the "database" driver can be used for direct database table access.

4. Using Auth Guards in Middleware

Laravel allows applying authentication guards in middleware to restrict access to certain users.

public function handle($request, Closure $next)
{
    if (!Auth::guard('admin')->check()) {
        return redirect('/login');
    }
    return $next($request);
}

This middleware ensures that only authenticated users using the "admin" guard can proceed.

5. Password Reset Configuration

Laravel includes password reset functionality, which can be configured as follows:

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_reset_tokens',
        'expire' => 60,
        'throttle' => 60,
    ],
],

The password reset expiration time helps improve security by making reset tokens short-lived.

6. Authenticating Users with Auth::guard()

The Auth::guard() method allows you to specify different authentication guards for users, admins, or other roles.

$user = Auth::guard('web')->user();
$admin = Auth::guard('admin')->user();

This method helps in implementing role-based authentication in applications.

7. Custom Authentication Guards

You can create a custom authentication guard by defining a custom driver:

use Illuminate\Support\Facades\Auth;

Auth::extend('custom-auth', function ($app, $name, array $config) {
    return new CustomGuard(Auth::createUserProvider($config['provider']));
});

This allows for fully customized authentication mechanisms.

8. Custom Authentication Guard Implementation

Here’s an example of a custom authentication guard that checks for an email and location ID:

public function attempt(array $credentials = [])
{
    $user = $this->provider->retrieveByCredentials(['email' => $credentials['email']]);
    if ($user && $user->location_id === $credentials['location_id']) {
        $this->user = $user;
        return true;
    }
    return false;
}

This ensures that authentication is successful only if both the email and location ID match.

9. Registering a Custom Provider

In Laravel, you must register a custom provider in AuthServiceProvider.php to handle custom authentication logic.

use App\Auth\CustomUserProvider;
use Illuminate\Support\Facades\Auth;

public function boot()
{
    Auth::provider('custom-provider', function ($app, array $config) {
        return new CustomUserProvider();
    });
}

Now, Laravel knows how to retrieve user data using the custom provider.

10. Logging in with a Custom Guard

To authenticate a user with a custom guard:

if (Auth::guard('custom')->attempt(['email' => 'user@example.com', 'location_id' => 123])) {
    return response()->json(['message' => 'Login successful']);
} else {
    return response()->json(['error' => 'Invalid credentials'], 401);
}

Laravel will attempt to authenticate using the "custom" guard, checking the email and location ID.

11. Conclusion

Laravel guards provide flexibility in handling multiple authentication methods, supporting different user roles and authentication mechanisms efficiently. You can use built-in guards like "web" and "api" or create fully customized authentication flows to fit your application's requirements.

Post a Comment

0Comments

Post a Comment (0)