Laravel multi auth protecting route multple middle

2019-08-28 23:54发布

问题:

I have created an extra middleware admin and I want to protect my routes. Adding one single middleware 'auth' or 'auth:admin' is working.

Route::get('/calendar', function () {
    return view('app', ['data' => []);
})->middleware('auth');

But I want that as an admin you can also access the user routes but this is not working. If I try the following, and I log in as an admin I get redirected to the login page all the time.

Route::get('/information', ['middleware' => ['auth', 'auth:admin'], function () {
    return view('app', ['data' => ['auth' => Auth::check()]]);
}]);

But if I change ['auth', 'auth:admin'] to ['auth:admin','auth'] it is working for admin but not for user. So it seems that only the first element of my middleware in array is being recognized. Does anybody have any idea why my multiple middlewares are working seperate but not together? Any help is appreciated

回答1:

If you are trying to allow multiple 'guards' to be checked for a route you can pass multiple guards as parameters to the Authenticate middleware, auth.

auth:web,admin (assuming web is your default guard).

This will try to resolve a user (Authenticatable) from each guard passed in. If any guard returns a user (Authenticatable) you pass through authenticated. If not you are a guest.

If you set the middleware auth and auth:admin those are 2 separate 'middleware' in the stack that are unrelated.