0
votes

I have some issues with Laravel authentication middleware. Because I want this middleware to run every time, I have created new middleware and added it to $middlewareGroups in API. My middleware looks like this:

if ($request->path() === 'api/auth/signin' OR 'api/canLogin' OR 'api/check') {
    return $next($request);
}
 elseif (!Auth::check()){
    return response()->json(['response' => false, 'status' => 403, 'message' => 'Not Authenticated'], 403);
}

Strange was that first time that actually worked (I don't know how), but now it doesn't. It always redirects me to public.html (because I don't have a login view).

I know that the easy way is to add that middleware to every protected route, but I want it to run every time. My routes uses auth middleware anyway (like so Route::group(['middleware' => ['auth:api']] ), if I delete this middleware it gives me same index.html

2
why you created a new middleware instead of using laravel one?Giacomo M

2 Answers

2
votes

OR doesnt work like that. Your IF will always return TRUE because it's a non empty string. It will result if (($request->path() === "string") OR (true) OR (true))

Instead you can use in_array($request->path(), ["path1", "path2", "etc"])

1
votes

don't use middleware overwired default unauthenticated exception

in Exceptions/Handler.php add this lines

use Illuminate\Auth\AuthenticationException;




protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
        ? response()->json(['response' => false, 'status' => 403, 'message' => 'Not Authenticated'], 403)
        : redirect('/login');
}

this is much better way to handel