我升级了:
"tymon/jwt-auth": "0.5.*",
从一个非常旧的版本开始,API 似乎已经发生了变化。我设法修复登录,使用:
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);
}
所以我的登录工作正常,但所有需要 token 的 API - 现在都失败了。
失败的 API 示例:
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;
}
知道如何使用新 API 将请求中的 token 转换为用户吗? 我找不到任何相关文档。
我尝试过:
返回response()->json(auth()->user());
但在此 API 中它返回空数组。仅在登录时有效。
最佳答案
尝试以下操作:
$user = JWTAuth::setRequest($request)->user();
您还可以在使用以下语法时显式设置保护:
// pass the guard in to the auth() helper.
return response()->json(auth('jwt')->user());
关于php - 升级后的 jwt-auth - 从请求 token 获取用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61122459/