21

I have a controller with the following in the constructor:

$this->middleware('guest', ['except' =>
    [
        'logout',
        'auth/facebook',
        'auth/facebook/callback',
        'auth/facebook/unlink'
    ]
]);

The 'logout' rule (which is there by default) works perfectly but the other 3 rules I have added are ignored. The routes in routes.php look like this:

Route::group(['middleware' => ['web']],function(){

    Route::auth();

    // Facebook auth
    Route::get('/auth/facebook', 'Auth\AuthController@redirectToFacebook')->name('facebook_auth');
    Route::get('/auth/facebook/callback', 'Auth\AuthController@handleFacebookCallback')->name('facebook_callback');
    Route::get('/auth/facebook/unlink', 'Auth\AuthController@handleFacebookUnlink')->name('facebook_unlink');
}

If I visit auth/facebook, auth/facebook/callback or auth/facebook/unlink whilst logged in I get denied by the middleware and thrown back to the homepage.

I've tried specifying the 'except' rules with proceeding /'s so they match the routes in routes.php exactly but it makes no difference. Any ideas why these rules are being ignored, whilst the default 'logout' rule is respected?

Cheers!

jd182
  • 3,180
  • 6
  • 21
  • 30

7 Answers7

48

You need to pass the method's name instead of the URI.

<?php
    
namespace App\Http\Controllers;
    
class MyController extends Controller {
    public function __construct() {
        $this->middleware('guest', ['except' => [
            'redirectToFacebook', 'handleFacebookCallback', 'handleFacebookUnlink'
        ]]);
    }
}

Since Laravel 5.3, you can use fluent interface to define middlewares on controllers, which seems cleaner than using multidimensional arrays.

<?php

$this->middleware('guest')->except('redirectToFacebook', 'handleFacebookCallback', 'handleFacebookUnlink');
Lucas Silva
  • 1,361
  • 1
  • 13
  • 18
4

I solved this issue in my Middleware by adding this inExceptArray function. It's the same way VerifyCsrfToken handles the except array.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class MyMiddleware
{
    /**
     * Routes that should skip handle.
     *
     * @var array
     */
    protected $except = [
        '/some/route',
    ];

    /**
     * Determine if the request has a URI that should pass through.
     *
     * @param Request $request
     * @return bool
     */
    protected function inExceptArray($request)
    {
        foreach ($this->except as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            if ($request->is($except)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // check user authed or API Key
        if (!$this->inExceptArray($request)) {
            // Process middleware checks and return if failed...
            if (true) {
              // Middleware failed, send back response
              return response()->json([
                'error' => true,
                'Message' => 'Failed Middleware check'
            ]); 
            }
        }
        // Middleware passed or in Except array
        return $next($request);
    }
}
cmac
  • 3,123
  • 6
  • 36
  • 49
2

If you are trying to follow the Laravel Documentation, an alternative solution to this is suggested by adding routes to the $except variable in the /Http/Middleware/VerifyCsrfToken.php file. The documentation says to add them like this:

'route/*'

But I found the only way to get it to work is by putting the routes to ignore like this:

'/route'
Tyler Pashigian
  • 457
  • 4
  • 13
2

When assigning middleware to a group of routes, you may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the withoutMiddleware method:

use App\Http\Middleware\CheckAge;

Route::middleware([CheckAge::class])->group(function () {
    Route::get('/', function () {
        //
    });

    Route::get('admin/profile', function () {
        //
    })->withoutMiddleware([CheckAge::class]);
});

for more information read documentation laravel middleware

Ozal Zarbaliyev
  • 566
  • 6
  • 22
1

Use this function in your Controller:

public function __construct()
    {
        $this->middleware(['auth' => 'verified'])->except("page_name_1", "page_name_2", "page_name_3");
    }

*replace page_name_1/2/3 with yours.

For me it's working fine.

Daljit Singh
  • 270
  • 3
  • 10
0

I have this solved, and here's what I am doing. Aso, I just realized this is very similar to what cmac did in his answer.

api.php

Route::group(['middleware' => 'auth'], function () {
    Route::get('/user', 'Auth\UserController@me')->name('me');
    Route::post('logout', 'Auth\LoginController@logout')->name('logout');
});

LoginController.php

class LoginController extends Controller
{
    use AuthenticatesUsers, ThrottlesLogins;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    // ...

    /**
     * If the user's session is expired, the auth token is already invalidated,
     * so we just return success to the client.
     *
     * This solves the edge case where the user clicks the Logout button as their first
     * interaction in a stale session, and allows a clean redirect to the login page.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $user = $this->guard()->user();

        if ($user) {
            $this->guard()->logout();
            JWTAuth::invalidate();
        }

        return response()->json(['success' => 'Logged out.'], 200);
    }
}

Authenticate.php

class Authenticate extends Middleware
{
    /**
     * Exclude these routes from authentication check.
     *
     * Note: `$request->is('api/fragment*')` https://laravel.com/docs/7.x/requests
     *
     * @var array
     */
    protected $except = [
        'api/logout',
    ];

    /**
     * Ensure the user is authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            foreach ($this->except as $excluded_route) {
                if ($request->path() === $excluded_route) {
                    \Log::debug("Skipping $excluded_route from auth check...");
                    return  $next($request);
                }
            }

            // code below here requires 'auth'

        { catch ($e) {
            // ...
        }

    }

I over-engineered it slightly. Today I only need an exemption on /api/logout, but I set the logic up to quickly add more routes. If you research the VerifyCsrfToken middleware, you'll see it takes a form like this:

    protected $except = [
        'api/logout',
        'api/foobars*',
        'stripe/poop',
        'https://www.external.com/yolo',
    ];

That's why I put that "note" in my doc above there. $request->path() === $excluded_route will probably not match api/foobars*, but $request->is('api/foobars*') should. Additionally, a person might be able to use something like $request->url() === $excluded_route to match http://www.external.com/yolo.

agm1984
  • 15,500
  • 6
  • 89
  • 113
0

You should pass the function name to 'except'.

Here's an example from one of my projects:

$this->middleware('IsAdminOrSupport', ['except' => [
        'ProductsByShopPage'
        ]
    ]);

This means the middleware 'IsAdminOrSupport' is applied to all methods of this controller except for the method 'ProductByShopPage'.

hackernewbie
  • 1,606
  • 20
  • 13