升级后的 jwt-auth - 从请求令牌获取用户
jwt-auth after upgrade - get user from request token
我升级了:
"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);
}
所以我的登录成功了,但是所有 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 将令牌从请求转换为用户吗?
我找不到任何关于它的文档。
我试过了:
return response()->json(auth()->user());
但在这个 API 中它 return 空数组。仅在登录时有效。
尝试以下操作:
$user = JWTAuth::setRequest($request)->user();
您也可以在使用以下语法时显式设置守卫:
// pass the guard in to the auth() helper.
return response()->json(auth('jwt')->user());
我升级了:
"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);
}
所以我的登录成功了,但是所有 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 将令牌从请求转换为用户吗? 我找不到任何关于它的文档。
我试过了:
return response()->json(auth()->user());
但在这个 API 中它 return 空数组。仅在登录时有效。
尝试以下操作:
$user = JWTAuth::setRequest($request)->user();
您也可以在使用以下语法时显式设置守卫:
// pass the guard in to the auth() helper.
return response()->json(auth('jwt')->user());