Home > Enterprise >  Laravel - How to cancel redirecting to login when unauthorized
Laravel - How to cancel redirecting to login when unauthorized

Time:11-01

In my project, I using laravel as api

UserController > profile() need token to run

For example when I call it without token, laravel display error which "Route [login] not defined" and it's right because we don't have any template in laravel.

How can I return json response instead redirect to login page as html?

public function profile(): JsonResponse
{
    //using protected method
    return response()->json($this->guard()->user());
}

CodePudding user response:

So basically what you can do is you can create a customized Auth middleware which returns a JSON response. Or you can use a simple condition in your function:

  if (Auth::check()){
      //if logged in user exists
  } else {
      //if logged in user does not exist
  }

CodePudding user response:

You can make middleware manually and in the middleware you can check user if exists. For example, if you use JWT token, then you can write like that as app/Http/Middleware/Authenticate.php :

   public function handle($request, Closure $next, $guard = null)
    {

        /* Check is token filled */
        if (!Auth::check()) {
            return response()->json([
                'success' => false,
                'status' => 401,
                'message' => 'Bad authorization',
                'data' => []
            ], 401);

        }

        return $next($request);
    }

For route partion:

Route::group([
    'middleware' => 'auth'
], function () {
  Route::get('/profile', 'User@profile');
});

CodePudding user response:

Open Authenticate file app/Http/Middleware/Authenticate.php

add reference

use Closure;
use Illuminate\Support\Facades\Auth;

put this code:

public function handle($request, Closure $next, ...$guards)
{
    if (!Auth::guard('api')->check()) {
        return response()->json(['message' => 'Error Message!']);
    }

    return $next($request);
}
  • Related