使用护照访问令牌获取用户数据-Laravel

时间:2019-12-26 15:17:44

标签: laravel laravel-5 jwt access-token

我一直在尝试使用访问令牌返回用户数据,但始终出现错误:

Invalid payload

我的方法是获取令牌,然后从oauth_access_tokens表中找到用户ID。我的代码如下:

public function authenticateUser($token){
     $user_id = DB::table('oauth_access_tokens')->where('id', trim($token))->value('user_id');
     $user = \App\User::find($user_id);

     Auth::login($user, true);
}

令牌是这样的:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjkyZGU3ZGYyMDcxZjgzMzU5YWUxMmRlYzM4ZGJiM2EyMTk0NzEyYTQ5NmRiNzgwZWJkMDg2Yjc0NThkZjU0NmFlZmU2Yzg0N2Q0Mjc5MDAxIn0.eyJhdWQiOiIxIiwianRpIjoiOTJkZTdkZjIwNzFmODMzNTlhZTEyZGVjMzhkYmIzYTIxOTQ3MTJhNDk2ZGI3ODBlYmQwODZiNzQ1OGRmNTQ2YWVmZTZjODQ3ZDQyNzkwMDEiLCJpYXQiOjE1NzczNzE4MDYsIm5iZiI6MTU3NzM3MTgwNiwiZXhwIjoxNjA4OTk0MjA1LCJzdWIiOiIzMCIsInNjb3BlcyI6W119.Io4xkJYEczbI7rhFD_UKAoe7v_1-RLJXjA6XqGIe2nRAWEgMkg-mokQUiGz41xYVazmDmACDwwYSRr-iTTzwc591NABfxsmMk7OdYkUKb93UTA3JhKClEGSP82y1QrIfm9XTZ0KKDaCKlfKqye1Aobj9zFthQdApegTaK61ReLQa7MzO6EM5fcZ3udsLL3QpKXFuyO6JcPKRauKIbA8oNIKEdadprLWJSeQieIyA8lpYOr453QzgZGgzCwPY1U2RmIbCzqyNQD_L5264-ix1503KxgPt4F_Cl82WXm7tNsZKNwE-vGKhCc2CcgAgTV1lIj7ItDf2KpDh_Jt96Uiv2eJ3OtXYvuOTErz9mNnQ1T38hxQmKDh8XlG3f7JgIWWzN6m8ItBV1KyGZi0-vn2HXetkZTNIyfJV8E5-RaGUzIKX7RejWd5BVaqFw0OjDYPeliVOaZzfcZCRnPDSJBGwf7YqJrRXP61LMasn_ZJ-i8G5JIaQx2vdmfYgE41O5F9fE5uEF5-mIV979RbnswL6CJsSGmmUMzC7mPhqL6HtPu2hMTnfHbKY0-efqtzZ5I2TBQU6ODM37RFN5TEljoEgBFG6kAImkGDy4QFH5uqt6V7-ZFxvrKQzQozgezSgA6ITF1sRb7yWfI-9rF7sYE_aKu3r1_KRr4UJLoZqFyvGPP0

不是我应该传递给上述函数的令牌。当我将其传递给base64_decode时,我看到了JSON对象以及其他乱码。我在这里做什么错了?

2 个答案:

答案 0 :(得分:0)

我以前从未使用过Laravel Passport,但是我可以想象使用令牌时已经对用户进行了身份验证。所以也许是这样的路线:

Route::get('/user', function(Request $request) {
    return Auth::user();
})->middleware('auth:api');

答案 1 :(得分:0)

最终,我通过向另一台机器上的api发送请求,同时在标头中添加令牌来达成此目的:

public function authenticateUser($token) {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request('GET', env('APP_API_URL') . '/api/v2/user_data', [
                'headers' => [
                    'Accept' => 'application/json',
                    'Authorization' => 'Bearer ' . $token,
                ],
            ]);

            $request = (string) $response->getBody();
            $request = json_decode($request);
            $user = User::where('email', $request->data->user->email)->first();
            Auth::login($user, true);
        } catch (RequestException $e) {
            dd('Something went wrong while connection to the api');
        }
    }