【问题标题】:JWT Retreiving the Authenticated user from a token in LaravelJWT 从 Laravel 中的令牌中检索经过身份验证的用户
【发布时间】:2020-05-27 04:17:32
【问题描述】:

当我在请求标头中传递用户的 jwt 令牌时,我只能获得该表中的用户信息

我有一个关系数据库,其中每个用户都将数据存储在另一个表中。 JWT 仅返回用户表中的用户详细信息(姓名、电子邮件等)。

在获取所有用户的列表时,我可以将他们的数据存储在另一个表中,但我不知道如何使用 jwt。

有人可以指导我吗?我正在使用 Laravel

这是用户资源

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\History;
use App\Http\Resources\History as HistoryResource;

class Admin extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'  => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'history' => HistoryResource::collection($this->history)
        ];
    }
}

这是获取用户的 jwt 控制器

public function getAuthenticatedUser()
{
    try {

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }

    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());

    }

    // the token is valid and we have found the user via the sub claim
    return response()->json(compact('user'));

}

【问题讨论】:

    标签: php laravel api jwt jwt-auth


    【解决方案1】:

    您的问题是 JWTAuth::parseToken()-&gt;authenticate() 返回 User 而不是用户资源 (Admin)。

    您只需要从$user 生成资源即可修复:

    $admin = new Admin($user);
    return response()->json(['user' => $admin]);
    

    【讨论】:

    • 它返回一个空数组
    • 您能否在创建管理资源之前验证$user 是否有效? dd($user)
    【解决方案2】:

    我只需这样做就可以修复它。

        $user = auth()->user();
        $admin = Admin::find($user);
        $return = AdminResource::collection($admin);   
        return response()->json($return);
    

    它返回了登录用户

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 2017-12-21
      • 2023-03-31
      • 1970-01-01
      • 2016-11-30
      • 2023-03-25
      • 2018-09-27
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多