php - 升级后的 jwt-auth - 从请求 token 获取用户

标签 php laravel laravel-5 jwt

我升级了:

"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/

相关文章:

php - Laravel 中的 session flash 消息超时

php - undefined variable : _ENV in Laravel 5. 3

php - Laravel 面包屑不选择 View

php - 在 DB_Connector 类中的何处放置 PDO 准备好的语句 - 在构造函数中还是在函数中?

php - 如何嵌套xpath查询

php - 500(内部服务器错误)与 Laravel 和 Docker

php - 在更改表迁移中将现有外键列设置为可为空

php - 使用 PDO 结果数据库时返回值中的额外(双)数组字段

php - 如何从命令行执行类中的方法

css - HTML5 桌面通知样式