PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

[FIXED] Using Laravel Auth middleware

 March 01, 2022     authentication, laravel, laravel-5.1, middleware, php     No comments   

Issue

Laravel 5.1 really had minimal documentation.. I need clear idea about how to protect routes using Auth middileware..

Documentation tells to add "middleware" => "auth" parameter to route. or can do

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

But How to use Auth middleware for actual user authentication and auto redirection to /login from protected routes ??


Solution

In Kernel.php - there are registered middlewares under protected $routeMiddleware like this:

/**
 * The application's route middleware.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];

You can see 'auth' is registered for using App\Http\Middleware\Authenticate.

Then you can follow this path - if you open /app/Http/Middleware/Authenticate.php, you will find public function handle:

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest())
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                return redirect()->guest('auth/login');
            }
        }

        return $next($request);
    }

and here is where redirection is managed, and you can modify it for your own needs, or you can create custom middleware.

finally - as it is written in documentation - in the controller, which will need to be authenticated, you will add

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

You can create a custom middleware if provided ones do not suit your needs.



Answered By - Angel M.
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing