Do I need to use auth middleware in the controller if I use Laravel's Gates?

0

Is it safe to remove an authentication middleware from a controller if I have already set a Gate on Laravel?

I did so:

No AuthServiceProvider.php

Gate::define( 'admin', function ( $user ) {
    return $user->cargo_id == '3';
} );

On the route

Route::middleware( 'can:admin' )->prefix( 'admin' )->group( function() {

    Route::get( '/', function() {

        return view( 'admin.home' );

    } );

In the controller I had:

public function __construct()
{

    $this->middleware( 'auth' );

}

When the user accesses the page, instead of redirecting to the login, removing the middleware from the controller returns a permission error directly. I prefer that, but is this correct in terms of security?

    
asked by anonymous 30.10.2018 / 13:01

1 answer

1

It does not make sense what you want to do.

One thing is auth middleware, another is Gate. One checks the authentication, another checks the permission.

The auth middleware is intended to allow user access when the user is authenticated. If it is not authenticated, Laravel returns 401 to JSON requests, or redirects to login in the case of a web request.

The purpose of Gate is to define what can be accessed by a particular user or not. An authenticated user can have access to one resource, and the other can not. And this is where the role of the Gate comes in!

For example, the user who has nivel_id 1 can see the register button, since what has the value 2 can not.

In this case, you would create a Policy or Gate::define that such a user can access that button. The return of a method or callback of Gate should return a boolean, to indicate whether the user has permission or not.

    
30.10.2018 / 13:33