I upgraded:
“tymon/jwt-auth”: “0.5.*”,
from a very old version, and it seems like the API has changed. I managed to fix the login, using:
public function login(Request $request) { $credentials = $request->only(['username', 'password']); $validator = Validator::make($credentials, [ 'username' => 'required', 'password' => 'required', ]); if($validator->fails()) { throw new ValidationHttpException($validator->errors()->all()); } if (!$token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } $user = auth()->user(); $user->ip_address = $request->ip(); if ($request->device_token) $user->device_token = $request->device_token; $user->save(); $data['token'] = $token; $data['email'] = $user->email; return response()->json($data); }
So my login work, but all API’s that required the token – fail now.
Example of API that fail:
class UserController extends Controller { public function __construct() { // $this->middleware('auth:api', ['except' => ['login']]); } public function enterWorld(Request $request) { $token = $request->input('token'); $user = JWTAuth::toUser($token); return $user; }
Any idea how to convert the token from the request to the user with the new API? I couldn’t find any docs about it.
I tried:
return response()->json(auth()->user());
but in this API it return empty array. only in login it works.
Advertisement
Answer
Try the following:
$user = JWTAuth::setRequest($request)->user();
You may also explicitly set the guard when using the following syntax:
// pass the guard in to the auth() helper. return response()->json(auth('jwt')->user());