Laravel Authentication


Laravel Authentication – The Laravel Authentication facility is made up of “Guards” and “Providers”. Guard define how user are authenticate for each request and provider define how user retrieve from your persistance storage.


Laravel Authentication.

Let us understand how to use laravel Authentication.

Function:-

There are some followings function available in laravel Authentication.

  • 1. Introduction.
  • 2. Authentication Quickstart.
  • 3. Manually Authenticating Users.
  • 4. HTTP Basic Authentication.
  • 5. Adding Custom Guards.
  • 6. Adding Custom User Providers.
  • 7. Events.

1. Introduction.

Laravel’s make implementing authentication very simple. Almost every thing is configure for you out of box. This file is located at config/auth.php which hold several well document option for tweaking the behavior of the authentication services.

Larvel authentication is using two way Guards and Providers. guards define user authentocation and providers define user retrieve from the storage.

Database Considerations

Laravel includes an App/User in your app directory. This model can be used with the default Eloquent authentication driver. If your application is not using eloquent, you can use the database authentication driver which uses the laravel query builder.

2. Authentication Quickstart.

Laravel ships with several pre-built authentication controller, which are located in the App/Http/controllers/Auth namespace. The RegisterController handles new user registration, the LoginController handles authentication, the ForgotPasswordController handles e-mailing links for resetting passwords and the ResetPasswordController contain the logic of reset password.

Routing

Laravel provides a way to scaffold all of the routes and views you need for authentication using a command.

php artisan make:auth

This Artsian command should be used on fresh application and will install a layout view, login view and registration views, as well as routes for all authentication end points.

Views

The php artsian make:auth command will create all of the views you need for authentication and place them at resources/views/auth directory.

All of these views use the bootstrap CSS framework but you are free to customize them.

Authenticating

By using authenticate controller we can setup route and views. If you want to register new user in your application, you can simply access your application in a browser with authenticate controller.

Path customization

When user successfully authenticated, it will be redirect to the /home page. We can customize the post authentication redirect location by defining a redirectTo property on the login, register andrestPassword Controller.

protected $redirectTo = '/';
protected function redirectTo()
{
    return '/path';
}

Username Customization

Laravel use by default email field for authentication. If you want to customize this,
you can define a username method on your LoginController.

public function username()
{
    return 'username';
}

Guard Customization

You can also customize the Guard which is used to authenticate and register users. Define a guard on your Login, Register and resetPassword Controller and return Guard instance.

Let’s look at a simple example.

use Illuminate\Support\Facades\Auth;

protected function guard()
{
    return Auth::guard('guard-name');
}

Retrieving The Authenticated User

You can access the authenticated user via Auth facade.

use Illuminate\Support\Facades\Auth;

$user = Auth::user();

$id = Auth::id();

Once a user is authenticated, you can access the authenticated use via an Illuminate/Http/Request instance.

Let’s look at a simple example.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class ProfileController extends Controller
{
    
    public function update(Request $request)
    {
        // $request->user() returns an instance of the authenticated user...
    }
}

Determining If The Current User Is Authenticated

If the user is already logged in your application, you can use the check method on the Auth facade and return true if the user is authenticated.

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

Protecting Routes

Laravel ship with an auth middleware, which is defined at Illuminate/Auth/Middleware/Authenticate. since this middleware already registered in your HTTP Kernel.

Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth');

Specifying A Guard

The guard specify should correspond to one of the key in the guard array of your auth.php configuration file.

public function __construct()
{
    $this->middleware('auth:api');
}

3. Manually Authenticating Users.

You will access laravel authentication service via the Auth facade. So you will make sure to import the Auth facade at the top of the class and then check out the attempt method.

Let’s look at a simple example.

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}

The attempt method will true if authentication was sucessfull otherwise it will return false.

Specifying Additional Conditions

You can also add extra condition to the authentication query in addition to the user’s email and password.

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) 
{
    //.......
}

Accessing Specific Guard Instances

The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file.

if (Auth::guard('admin')->attempt($credentials)) {
    //.....
}

Logging Out

For logout you can use logout method on the Auth facade

Auth::logout();

Remembering Users

If you want to provide remeber me functionality in your application, you can pass a boolean value as the second argument to the attempt method which will keep the authentication indefinitely or untill they manually logout.

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
    // The user is being remembered...
}
if (Auth::viaRemember()) 
{
    //
}

Other Authentication Methods

Authenticate A User Instance

If you need to log an existing user instance into your application, you can call the login method with the user instance.

Auth::login($user);

// Login and "remember" the given user...
Auth::login($user, true);

You can specify the guard instance you want to use.

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

Authenticate A User By ID

If the user login in your application by their ID, you can use the loginUsingId method.

Auth::loginUsingId(1);

// Login and "remember" the given user...
Auth::loginUsingId(1, true);

Authenticate A User Once

If the user want to login in the application for a single request, you can use once
method.

if (Auth::once($credentials)) {
    //
}

4. HTTP Basic Authentication.

It provides a quick way to authenticate users of your application without setting up a dedication login page. Attach the auth.basic middleware to the controller.

Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth.basic');

A Note On FastCGI

If we are using PHP FastCGI, HTTP basic authentication can not work correctly out of the box.Then following code should be added in .htaccess file.

RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Stateless HTTP Basic Authentication

You can also use HTTP basic authentication without setting a user identifier cookie in the session, which is particularly useful for API authentication

Let’s look at a simple example.

<?php
namespace Illuminate\Auth\Middleware;
use Illuminate\Support\Facades\Auth;

class AuthenticateOnceWithBasicAuth
{
    public function handle($request, $next)
    {
        return Auth::onceBasic() ?: $next($request);
    }

}

Then register the route middleware and attach it to a route.

Route::get('api/user', function () {
    // Only authenticated users may enter...
})->middleware('auth.basic.once');

5. Adding Custom Guards.

We can define authentication guards using the extend method on the auth
facade. We should place this call to provider within a service provider.

Let's look at a simple example.

<?php
namespace App\Providers;
use App\Services\Auth\JwtGuard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
   
    public function boot()
    {
        $this->registerPolicies();

        Auth::extend('jwt', function ($app, $name, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\Guard...

            return new JwtGuard(Auth::createUserProvider($config['provider']));
        });
    }
}

The callback passed to the extend method should return an implementation of Illuminate/Contracts/Auth/Guards. If you custom guard has been defined, you can use this guard in the guards configuration in your auth.php file.

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

6. Adding Custom User Providers.

If you are not using a traditional relational database to store your users, you will need to extend Laravel with your own authentication user provider.

Let's look at a simple example.

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use App\Extensions\RiakUserProvider;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerPolicies();

        Auth::provider('riak', function ($app, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\UserProvider...

            return new RiakUserProvider($app->make('riak.connection'));
        });
    }
}

After that registered the provider using the provider method, you can switch to the new user provider in your auth.php configuration file.

'providers' => [
    'users' => [
        'driver' => 'riak',
    ],
],

You can use this provider in your guards configuration.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

The User Provider Contract

The Illuminate/Contracts/Auth/UserProvider implementation are only responsible for fetching a Illuminate/Contracts/Auth/Authenticable implementation out of a persistant storage system, Such as MySql, Riak etc.

Let's look at a simple example.

<?php
namespace Illuminate\Contracts\Auth;

interface UserProvider {

    public function retrieveById($identifier);
    public function retrieveByToken($identifier, $token);
    public function updateRememberToken(Authenticatable $user, $token);
    public function retrieveByCredentials(array $credentials);
    public function validateCredentials(Authenticatable $user, array $credentials);

}

The retrieveById function is used to recieve a key representing the user.

The retrieveByToken function is used to retrieve a user by their unique $identifier and remeber me $token, stored in field remeber_token.

The updateRememberToken function is used to update the user field.

The retrieveByCredentials method is used to recieve the array of credential passed to the Auth::attempt method when attempting to sign into an application.

The validateCredentials is used to compare the given user with the credentials to authenticate the user.

The Authenticatable Contract

We have investigate each of the method on the userProvider. Remeber provider should return implementation of this interface from the retrieveById and retrieveByCredentials method.

Let's look at a simple example.

<?php
namespace Illuminate\Contracts\Auth;

interface Authenticatable {

    public function getAuthIdentifierName();
    public function getAuthIdentifier();
    public function getAuthPassword();
    public function getRememberToken();
    public function setRememberToken($value);
    public function getRememberTokenName();

}

7. Events.

Laravel Raise a vareity of events during the authentication process.

Let's look at a simple example.

protected $listen = [
    'Illuminate\Auth\Events\Registered' => [
        'App\Listeners\LogRegisteredUser',
    ],

    'Illuminate\Auth\Events\Attempting' => [
        'App\Listeners\LogAuthenticationAttempt',
    ],

    'Illuminate\Auth\Events\Authenticated' => [
        'App\Listeners\LogAuthenticated',
    ],

    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogSuccessfulLogin',
    ],

    'Illuminate\Auth\Events\Failed' => [
        'App\Listeners\LogFailedLogin',
    ],

    'Illuminate\Auth\Events\Logout' => [
        'App\Listeners\LogSuccessfulLogout',
    ],

    'Illuminate\Auth\Events\Lockout' => [
        'App\Listeners\LogLockout',
    ],
];

Advertisements

Add Comment

📖 Read More