Kingsley Akindele
Kingsley Akindele

Reputation: 361

Laravel JWT Return Token But Returns Unauthenticated On Subsequent Request

I keep having this issue that whenever I log-in, I get my jwt token, but whenever I try to use that token to make other requests on differents route that are binded with the auth:api middleware, it keeps returning unauthenticated. hence, I can't make any request.

can anybody please help

Route looks like

Route::prefix('auth')->group(function () {

Route::post('login', [LoginController::class, 'login'])->name('login');
Route::post('refresh', [LoginController::class, 'handleRefreshToken'])->name('refresh');
Route::post('me', [LoginController::class, 'userDetails'])->name("user_details");
});

why my controller looks like

<?PHP

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginController\LoginValidator;
use App\Traits\SendsApiResponse;
use Illuminate\Http\Response;

class LoginController extends Controller
{
use SendsApiResponse;

/**
 * Create a new AuthController instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth:api', ['except' => ['login', 'refresh']]);
}

/**
 * Handles User Login
 * @param LoginValidator $request
 * @return \Illuminate\Http\JsonResponse|mixed
 */
public function login(LoginValidator $request)
{
    try {
        $login_cred = $request->validated();
        $token = auth()->attempt($login_cred);
        if (!$token) {
            return $this->failureResponse("Incorrect UserName and/or Password", Response::HTTP_UNAUTHORIZED);
        }

        return $this->successResponse($this->returnToken($token));
    } catch (\Exception $e) {
        return $this->failureResponse($e->getMessage(), $e->getCode());
    }
}

public function returnToken($token)
{
    return [
        "token" => $token
    ];
}

/**
 * Handle The Refreshing Of Users Token
 * @return \Illuminate\Http\JsonResponse|mixed
 */
public function handleRefreshToken()
{
    try {
        return $this->successResponse($this->returnToken(auth()->refresh($forceForever = true)));
    } catch (\Exception $e) {
        return $this->failureResponse($e->getMessage(), 440);
    }
}

public function userDetails()
{
    return $this->successResponse(auth()->user());
}

}

of all the method above, only login works, the rest don't

Upvotes: 3

Views: 1593

Answers (1)

Miguel Nogueira
Miguel Nogueira

Reputation: 11

Depending on how you're sending the token:

This package will always return Unauthenticated when the token is missing, expired, or wrong. Add the Authorization header with Bearer [your token] to the request and send it again, then check if it still returns Unauthenticated.

The code that handles this logic is contained in the auth:api middleware, but it only works if you configured it correctly in the config/auth.php file.

Upvotes: 1

Related Questions