Laravel API response Unauthenticated even when Authentication is passed

8.4k Views Asked by At

I am using the jwt for creating the tokens while login. After I login, I try to hit the /me api pointing to the function:

     public function me()
        {
            $user = auth()->user();
            return response()->json($user);
        }

I followed the JWT official documentation, initially I was able to get the response for the API. Suddenly it started throwing a

{
    "message": "Unauthenticated."
}

Why is this happening?? Is there any workaround? It would be great if someone could help.

2

There are 2 best solutions below

4
On BEST ANSWER

i tried documentation setup and worked fine, you might missed passing authentication header in your api call. since idk what's your setup i can only tell when you logged in, you should use received token in api calls with authentication.

PostMan Software: In headers tab add a key as Authorization and assign token for value with Bearer, like Breaer token......

for more help please clarify how you're trying api calls.

Edit: added an alternate way for using middleware

Another way of implementing or using middleware :

Create a Middleware with JWT name and put below code in handle function

Don't forget to import
use JWAuth;

public function handle($request, Closure $next)
{
    JWTAuth::parseToken()->authenticate();
    return $next($request);
}

Then in Kernel add jwt to $routeMiddleware like this :

protected $routeMiddleware = [
    // you should add below code.
    'jwt' => \App\Http\Middleware\JWT::class,
];

in routes/api

Route::apiResource('/posts', 'PostController');

now in PostController add your middleware to Constructor like this.

public function __construct()
{
    $this->middleware('jwt', ['except' => ['index','show']]);
}

So in construct you will set your middleware base on JWT, then with except you can modify which one of your functions don't need to authentication base on JWT token. now when you use auth()->user() you can get your info or etc.

So if i had index, show, update, delete, store, create when i try to do API call if i use GET METHOD for url.com/posts or url.com/posts/23 i can get my posts without passing JWT token.

When you tried to use JWT you should realize that it's working base on token you're passing, you're getting token when you using login, but you're not getting user info because you're not passing user's token to app, before all of this you should consider to verify token then do the rest Logics. Good Luck.

Edit : added more info

auth.php

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],
0
On

In case anyone has the same problem, and the selected solution do solve it. Check the following: if you go alway respose{ "message": "Unauthenticated." } The solution is adding this to .htaccess of root folder (not only inside the public folder)

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]