lundi 23 décembre 2019

Laravel role-based authentication with middleware

I want to refuse access to some of my pages with the help of Laravel’s middleware. I followed these tutorials: Dan Englishby and everton zp

I've created the User and Role model as well as the database entries over migration and seeder. Now I want to use the middleware.

web.php

Route::get('/', function () {
  return view('start')->middleware('auth:admin');
});

Just for testing I want to grant access to admin users only. Therefor I've added :admin as a parameter to the middleware

/app/Http/Middlewarae/Authenticate.php

<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use App\User;

class Authenticate extends Middleware
{
    protected function redirectTo($request)
    {

            return route('login');
            //abort(401, 'Sie haben keine Berechtigung für diese Aktion');

    }

    public function handle( Request $request, Closure $next, ...$roles ) {       
      if( \Auth::check() && $request->user()->authorizeRoles($role)  != null ) {
        if( !$request->user()->authorizeRoles($roles) ) {
          abort(401, 'Sie haben keine Berechtigung für diese Aktion');
        }

        // TODO 

        return $next($request);
      }
      return redirect('/login');
    }
}

Now I get the following warning:

Declaration of App\Http\Middleware\Authenticate::handle(App\Http\Middleware\Request $request, App\Http\Middleware\Closure $next, ...$roles) should be compatible with Illuminate\Auth\Middleware\Authenticate::handle($request, Closure $next, ...$guards)

Taking a look in /vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php or in Laravel API Documentation shows that the declarations are pretty the same (as also the warning text does)

Where is my mistake?

Later, I want to have the possibility to use the authentication with Laravel's middleware and in blade with @if (Auth::user()->hasRole("admin"))



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire