DEV Community

keikesu0122
keikesu0122

Posted on

How to authenticate users on Laravel using middleware

1.add a route for login

Route::post('/login', 'auth@login');
Enter fullscreen mode Exit fullscreen mode

2.make a controller and method for login

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Util\authorizer;

class auth extends Controller
{
    public function __construct()
    {
        $this->authorizer = new authorizer();
    }

    public function login(Request $request)
    {
        $id = $request->post('userId');
        $pw = $request->post('password');

        $this->authorizer->authUser($id, $pw);

    }
}
Enter fullscreen mode Exit fullscreen mode

The authUser actually authenticates users, so the next step is to make this method.

3.make a method to authenticate a user

touch app/Models/Utils/authorizer.php
Enter fullscreen mode Exit fullscreen mode
<?php

namespace App\Models\Util;

use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Session;

class authorizer extends Model
{
    public function __construct()
    {
        $this->users = new \App\Users();
    }

    //obtain a record from User table and verify the entered userId and password
    public function authUser($id, $pw)
    {
        if (is_null($id)) return false;
        if (is_null($pw)) return false;
        $user = $this->users::where('userId',$id)->get();
        if ($user === False) return false;
        if (count($user) == 0 || !isset($user['pw'])) return false;
        if (password_verify($pw, $user['pw'])) {
            $this->setAuthSession($user);
        } 
    }

    // add userId to session
    private function setAuthSession($data)
    {
        if (isset($data['userId'])) request()->session()->put('userId', $data['userId']);
        request()->session()->save();
    }
}
Enter fullscreen mode Exit fullscreen mode

At this point, a login function has been mounted. The next step is to distinguish unauthorized users from authorized users.

4.make a middlerware

php artisan make:middleware Authentication
Enter fullscreen mode Exit fullscreen mode
<?php

namespace App\Http\Middleware;

use Closure;

class Authentication
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        //check the session information for auchentication
        if($request->session()->get('userId')==null){
            return response()->json(array('status' => 'NG'),403);
        }
        return $next($request);
    }
}
Enter fullscreen mode Exit fullscreen mode

5.add the middleware to Kernel.php to use it

/**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        //'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'authentication' => \App\Http\Middleware\Authentication::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
Enter fullscreen mode Exit fullscreen mode
  1. add a route group to your route file
Route::group(['middleware' => ['authentication']], function () {
   Route::get('/userlist', 'users@getUserList');
});
Enter fullscreen mode Exit fullscreen mode

By adding routes in the group, the middleware function (in this case authentication) is implemented so that unauthorized users can't reach /userlist.

Top comments (0)