简体   繁体   English

JWT 从 Laravel 中的令牌中检索经过身份验证的用户

[英]JWT Retreiving the Authenticated user from a token in Laravel

When I pass user's jwt token in the request header, I only get the user info which is in that table当我在请求标头中传递用户的 jwt 令牌时,我只获得该表中的用户信息

I have a relational database in which each users have data stored in another table.我有一个关系数据库,其中每个用户都将数据存储在另一个表中。 JWT only returns the users details from the user's table (name, email etc. just that). JWT 只返回用户表中的用户详细信息(姓名、电子邮件等)。

While fetching list of all users I can get their data stored in the other table but I don't know how to do it with jwt.在获取所有用户的列表时,我可以将他们的数据存储在另一个表中,但我不知道如何使用 jwt。

Can anyone guide me with that?任何人都可以指导我吗? I'm using Laravel我正在使用 Laravel

This is the User resource这是用户资源

<?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)
        ];
    }
}

And this is the jwt controller for fetching user这是用于获取用户的 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'));

}

Your problem is that JWTAuth::parseToken()->authenticate() returns a User and not a User Resource ( Admin ).您的问题是JWTAuth::parseToken()->authenticate()返回User而不是用户资源( Admin )。

You just need to generate the resource from the $user to fix:您只需要从$user生成资源即可修复:

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

I was able to fix it by simply doing this.我能够通过简单地这样做来修复它。

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

It returned the logged in user它返回了登录用户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM