簡體   English   中英

Tymon JWT user_not_found - Laravel 5.1

[英]Tymon JWT user_not_found - Laravel 5.1

我正在為移動應用程序構建 api,並且我正在使用 JWT 來驗證用戶。 我正在嘗試在 Laravel 5.1 中實現它。

每當我使用由身份驗證方法提供給我的令牌時,我都會收到錯誤消息: {"error":"user_not_found"}

我的流程:

  1. 使用Auth::attempt($credentials)驗證用戶
  2. 使用$user = User::where('user_id', Auth::user()->user_id)->first();從數據庫中獲取用戶$user = User::where('user_id', Auth::user()->user_id)->first();
  3. 為用戶設置令牌使用

    $token = ""; try { // attempt to verify the credentials and create a token for the user if (! $token = JWTAuth::fromUser($user)) { return response()->json(['error' => 'invalid_credentials'], 401); } } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'could_not_create_token'], 500); }

它使用此方法返回令牌:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOm51bGwsImlzcyI6Imh0dHA6XC9cL3BlZGxyLmRldlwvYXBpXC9sb2dpbiIsImlhdCI6MTQ0OTk2NDQ2NywiZXhwIjoxNDQ5OTY4MDY3LCJuYmYiOjE0NDk5NjQ0NjcsImp0aSI6IjJlMDMyMjA5MjMyZWM1MDVlY2I3YzE4ODFjNDk1MzFmIn0.tbO_fv4WDQ6WgiHtyYJAq2rjnOtaYPq85VO2ja2YVzw

但是當嘗試使用令牌對用戶進行身份驗證時,它會拋出錯誤{"error":"user_not_found"}

我的路線.php:

Route::any('/login', ['as' => 'login', 'uses' => 'APIController@postLogin']);
Route::group(['middleware' => 'jwt.auth'], function()   {
    Route::any('/users', ['as' => 'users', 'uses' => 'UsersController@getUsers']);
});

如果我取出中間件組,我可以訪問/users路由。 我認為它發生在Tymon\\JWTAuth\\Middleware命名空間的GetUserFromToken類中的某個地方,因為這是唯一列出錯誤user_not_found

我的數據庫使用user_id ,而不僅僅是id作為主鍵,這可能是問題嗎?

最后我明白了。

我進入了在發布JWTAuthServiceProvider時創建的config/jwt.php文件,然后我將identifier更改為我的 Users 表的主鍵(因為user設置被設置為App\\User ,我的主鍵是user_id在用戶模型)。

'identifier' => 'user_id' // somewhere around line 79

它奏效了。

您需要一個登錄路由,它首先創建一個會話。 然后獲取用戶。

Route::post('sessions/create', ['uses' => 'Auth\JwtAuthController@authenticate']);
Route::get('sessions/user', ['uses' => 'Auth\JwtAuthController@getAuthenticatedUser']);

在控制器中嘗試以下代碼:

/**
 * Authenticate by credentials
 */
public function authenticate()
{

    $credentials = request()->only('email', 'password');

    try {

        if ( !$token = JWTAuth::attempt($credentials) ) {
            return $this->error('invalid-credentials', 401);
        }

    } catch (JWTException $e) {
        // something went wrong whilst attempting to encode the token
        return $this->error('could-not-create-token', 500);
    }

    return response()->json(compact('token'));

}


/**
 * Get the user by jwt token, or return an error
 *
 * @return Response
 */
public function getAuthenticatedUser()
{

    try {

        if ( !$user = JWTAuth::parseToken()->authenticate() ) {
            return $this->error('user-not-found', 204);
        }

    } catch (TokenExpiredException $e) {

        return $this->error('token-expired', 401);

    } catch (TokenInvalidException $e) {

        return $this->error('token-invalid', 401);

    } catch (JWTException $e) {

        return $this->error('token-absent', 400);

    }

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


/**
 * Error formatter
 *
 * @param  string  $message
 * @param  integer $statuscode
 *
 * @return \Illuminate\Http\JsonResponse
 */
private function error($message, $statuscode = 401)
{
    return response()->json(['error' => $message], $statuscode);
}

解決方案...

如果您的代碼正確,那么如果您獲得輸出:

{
  "error": "invalid_credentials"
}

只需按照以下步驟操作:--------------

第一步檢查:

dd($request->only('email', 'password')); dd($credentials); // 輸出應該是這樣的..

array:2 [
  "email" => "myemail@myemail.com"
  "password" => "test123"
]

第二步檢查:

 dd($token); 

// 輸出應該是:false

第三步檢查:

1) 在app/Http/Kernel.php確保\\App\\Http\\Middleware\\VerifyCsrfToken::class被注釋掉。 2) 在config/jwt.php確保將標識符設置為用戶表的主鍵。

'identifier' => 'userid' // 默認設置為 'id'

最后一步轉到:App\\Config\\auth.php

在線編號:70 更改您保存模型的模型位置(用戶)

例如: App\\Model\\Myuser\\User

在線編號:71 將表名稱更改為您在模型中設置的名稱(用戶)

例如: protected $table = 'my_user';

 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Myuser\User::class,
            'table' => 'my_user'
        ],

它可能會幫助你......

試試看:在用戶模型中寫一行: protected $primaryKey = 'user_id' ;

例子:

class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'my_user';
    protected $primaryKey = 'user_id';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM