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.
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 withBearer
, likeBreaer 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
Then in Kernel add jwt to $routeMiddleware like this :
in
routes/api
now in PostController add your middleware to Constructor like this.
So in construct you will set your
middleware
base on JWT, then withexcept
you can modify which one of your functions don't need to authentication base on JWT token. now when you useauth()->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 useGET METHOD
forurl.com/posts
orurl.com/posts/23
i can get my posts without passingJWT
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