【问题标题】:Error while getting authenticated user in Laravel using JWT使用 JWT 在 Laravel 中获取经过身份验证的用户时出错
【发布时间】:2018-04-18 06:48:39
【问题描述】:

我能够在 laravel 中使用 JWT 登录并获取用户令牌。但是,在尝试通过传递该令牌来获取经过身份验证的用户 (getAuthUser) 时,我收到以下错误:

"SQLSTATE[42S22]: 找不到列: 1054 未知列 '' 在 'where 子句' (SQL: select * from user where `` = 12 limit 1)"

身份验证控制器:

<?php
namespace Modules\Authentication\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use JWTAuth;
use JWTAuthException;

use Modules\Settings\Entities\Users;
use Modules\Authentication\Http\Requests\Authentication;
class AuthenticationController extends Controller
{

public function __construct()
{
    // $this->user = new Users;
     $this->guard = \Auth::guard('api');
}

public function login(Authentication $request){
   $credentials = $request->only('username', 'password');

    try {
        // verify the credentials and create a token for the user
        $token = JWTAuth::attempt($credentials);


        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    // if no errors are encountered we can return a JWT
    return response()->json(compact('token'));
}

public function getAuthUser(Request $request){

    $user = JWTAuth::user($request->token);  
    // dd($user);      
    return response()->json(['result' => $user]);
}
}

用户模型:

namespace Modules\Settings\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;

use Tymon\JWTAuth\Contracts\JWTSubject;

class Users extends Model implements JWTSubject,Authenticatable{

Protected $table="user";
// protected $primaryKey = 'id';
protected $fillable = ['id','username','password','user_status_type_id','client_id','created_userid'];

protected $hidden = [
    'password', 'remember_token',
];

public function user_status(){

     return $this->belongsTo('Modules\Settings\Entities\UserStatusType','user_status_type_id');
}

public function user_client(){

    return $this->belongsTo('Modules\Settings\Entities\Client','client_id');

}


 public function role()
{
      return $this->belongsToMany('Modules\Settings\Entities\Role','user_role','user_id','role_type_id');
}

public function getAuthPassword() {
    return $this->password;
}


public function getJWTIdentifier()  {
    return $this->getKey(); 
}

public function getJWTCustomClaims()
{
return [];
}

public function getAuthIdentifierName(){}

public function getAuthIdentifier(){}

// public function getAuthPassword(){}
public function getRememberToken(){}
public function setRememberToken($value){}
public function getRememberTokenName(){}

}

路线:

Route::group(['middleware' => 'web', 'prefix' => 'api/v1/authentication', 'namespace' => 'Modules\Authentication\Http\Controllers'], function(){

Route::post('auth/login', 'AuthenticationController@login');
// Route::group(['middleware' => 'jwt.auth'], function () {
Route::get('user', 'AuthenticationController@getAuthUser');
// });
});

我正在邮递员中测试它 GET: ..../api/v1/authentication/user?token={Token}

编辑: 现在我在控制器中的 getAuthUser 方法如下所示:

 public function getAuthUser(Request $request){

    // $token = JWTAuth::getToken();
    // dd($token);


   $input = $request->all();
   JWTAuth::setToken($input['token']);
    // dd($input['token']);
    $user = JWTAuth::toUser($input['token']);  
    // dd($user);      
    return response()->json(['result' => $user]);
}

JWTAuth.php

public function authenticate()
{
   // dd($this->getPayload()->get('sub'));
    $id = $this->getPayload()->get('sub');
    // dd($id);
    // dd($this->auth->byId($id));

    if (! $this->auth->byId($id)) {
        return false;
    }

    return $this->user();
}

在这里,通过执行 dd($id),id 的值来了,但是如果我尝试执行 dd($this->auth->byId($id)),我会得到与以前相同的错误。

【问题讨论】:

  • 我认为您编辑了 where 并删除了潜在的敏感信息,否则似乎 sql 搜索可能缺少输入,您是否也检查了数据库?
  • 未编辑。这就是我得到的。
  • 似乎$this-&gt;getKey() 没有产生id 字符串。检查一下。
  • @Ohgod为什么要在 getAuthUser 时去那里?它在我登录时生成 id,但在执行 getAuthUser 时不生成。
  • 好吧,sql调用需要引用一些东西,似乎它目前试图引用任何东西,我发现有帮助的是添加'echo $value'作为各种断点,这样你就可以看到什么您的数据状态是

标签: php laravel authentication jwt


【解决方案1】:

试试这个来检索用户:

public function getAuthUser()
{
    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(['result' => $user]);
}

取自文档,Retreiving the Authenticated user from a token

编辑: 可能没有什么不同,但只是再次查看您的模型,我会说它需要是

class Users extends Authenticatable implements JWTSubject

而不是

class Users extends Model implements JWTSubject,Authenticatable

【讨论】:

  • 也许我在配置文件中遗漏了一些东西,有什么你想看的文件吗?
  • 这似乎与您的 primaryKey 和用作“子”声明的标识符有关。正如@Ohgodwhy 提到的,我会在调用$this-&gt;getKey() 时检查你的模型是否返回'id',假设你的用户表的主键是'id'
  • 看来这就是问题所在,请查看我的问题中已编辑的部分我能够获得“子”ID,但之后出现相同的错误。
  • 您是否按照我在答案编辑中提到的那样修复了您的课程?
  • 是的,这样做会给出“Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN) Class Modules\Settings\Entities\Users cannot extend from interface "错误
猜你喜欢
  • 1970-01-01
  • 2018-11-26
  • 2018-05-04
  • 2019-07-22
  • 2016-06-30
  • 2020-10-20
  • 2011-05-07
  • 1970-01-01
  • 2020-06-26
相关资源
最近更新 更多