0

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

1
  • why you created a new middleware instead of using laravel one? Commented Dec 14, 2020 at 8:31

2 Answers 2

2

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"])

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Maybe but I still have same respond

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.