0
It’s safe to remove an authentication middleware from a controller if I’ve already set a Gate on Laravel?
I did so:
In Authserviceprovider.php
Gate::define( 'admin', function ( $user ) {
return $user->cargo_id == '3';
} );
En route
Route::middleware( 'can:admin' )->prefix( 'admin' )->group( function() {
Route::get( '/', function() {
return view( 'admin.home' );
} );
On 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 directly returns a permission error. I prefer it that way, but this is correct in terms of security?
What doesn’t make sense? I read the documentation from the library, I understood the role of authentication and the Gate, about this apparently all ok. My doubt is what this above.
– user3681
It makes no sense to want to use the
Gate
without the authentication middleware.– Wallace Maxters
I’m sorry to insist, but I need to know, why doesn’t it make sense? In my case, without auth in the controller, the unauthenticated user, instead of being redirected to the login page, sees a 403. And the authenticated user who doesn’t have access also sees a 403. Apparently it worked, my question is whether this is somehow wrong in terms of safety.
– user3681
This is why I am asking - https://laravel.com/docs/5.7/authorization#guest-users. Where it says "By default, all Gates and policies Automatically Return false if the incoming HTTP request was not initiated by an authenticated user. "
– user3681
@Flavio You just said yourself why you were wrong by accident. When the user is not authenticated, he cannot see
403
. The right code for unauthenticated user is401
. The403
should be used for when the person is authenticated, but cannot access the resource. The401
should be used to identify that there is no authentication. They are two different things. That’s why I said it makes no sense. You would need to understand this point. Even if the documentation says it does so by default, the return status will go wrong. It’s better to go the right way than the easy way.– Wallace Maxters
I see what you mean. I added the middleware to Rota, it was like this - Route::middleware( [ 'auth', 'can:admin' ] ) - when the user tries to access it first asks for authentication. After authentication, if the user does not have access see 403.
– user3681
That’s right, that’s right
– Wallace Maxters