【问题标题】:jwt-auth after upgrade - get user from request token升级后的 jwt-auth - 从请求令牌中获取用户
【发布时间】:2020-07-22 03:35:49
【问题描述】:

我升级了:

"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 将令牌从请求转换为用户吗? 我找不到任何关于它的文档。

我试过了:

返回响应()->json(auth()->user());

但在这个 API 中它返回空数组。仅在登录时有效。

【问题讨论】:

    标签: php laravel laravel-5 jwt-auth


    【解决方案1】:

    尝试以下方法:

    $user = JWTAuth::setRequest($request)->user();
    

    您也可以在使用以下语法时显式设置保护:

    // pass the guard in to the auth() helper.
    return response()->json(auth('jwt')->user());
    

    【讨论】:

    • 谢谢,我刚刚注意到从我的登录示例返回的令牌是true,所以这个方法什么也不返回。有什么想法吗?
    • 你的用户模型中添加Tymon\JWTAuth\Contracts\JWTSubject接口了吗?
    • 是的,我加了这个接口
    • 我会接受答案并为此打开新的
    猜你喜欢
    • 2016-07-18
    • 2017-01-06
    • 2021-10-18
    • 2018-12-04
    • 1970-01-01
    • 2017-04-17
    • 2018-08-01
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多