1
votes

Currently to add authentication I use this in my routes file:

Route::middleware(['auth'])->group(function () {
});

But I want to also check for different routes if the user is an admin, so currently I do this and have a custom middleware file:

Route::middleware(['auth', 'admin'])->group(function () {
});

//

<?php 

namespace App\Http\Middleware;

use Closure;

class Admin {

    public function handle($request, Closure $next)
    {

        if ( Auth::check() && Auth::user()->isAdmin() )
        {
            return $next($request);
        }

        return redirect('dashboard');

    }

}

This all works fine, but I noticed with the api middleware it uses this:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Questions

  1. How can I make a namespaced auth middleware like the api one 'auth:admin'
  2. Where is the file located that sets the 'auth:api' middleware, I could not find it anywhere in the app folder
  3. Is there any other ways to do multiple auth like editing the file config/auth.php and then separating the users between two tables, one for admins and one for other users.
2

2 Answers

0
votes

auth:api is actually the basic auth middleware with the string api as a parameter. This means the user is authenticated using the api authentication guard

You could use auth:admin out of the box if you added a custom authentication guard for the admins.

0
votes

The auth middleware accepts one parameters which is the guard(s) to use. As you can see in Illuminate\Auth\Middleware\Authenticate middleware.

You can add custom auth guards. So you can create auth:admin if you'd like. But I do think it's perfectly fine to use one middleware to verify that the user is who he is (authentication) and a second one to verify that the user is allowed to visit the page he/she wants to visit (authorization).