0

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 Answers2

1

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',
    ],
],
Atlas-Pio
  • 1,063
  • 11
  • 26
  • Thanks @Atlas-Pio. This raised another error "The token could not be parsed from the request." Any idea what this is? Tried all the fixes in the other StackOverflow posts. Doest seem to work. – Mugundh Muthuvel Aug 13 '20 at 05:23
  • ```Route::group(['middleware' => ['jwt']], function () { Route::get('me', 'Api\AuthController@me'); });``` This is the route i m trying to hit from the Postman with ```Accept: application/json``` and the Bearer token in Authorization (received after login) as header. – Mugundh Muthuvel Aug 14 '20 at 03:26
  • earlier I was using the ```auth:api``` middleware and changed it as per your guidance from the above comment @Atlas-Pio – Mugundh Muthuvel Aug 14 '20 at 03:28
  • Man thanks a lot. I rechecked it with your comment. I think my middleware wasn't set right. Couldn't figure it out as I am just learning Laravel. Thanks a lot. You are a savior man! – Mugundh Muthuvel Aug 16 '20 at 04:00
1

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}]
Rafael Abne
  • 11
  • 1
  • 2