Laravel: JWT身份验证 auth()->user() 返回null

huangapple go评论54阅读模式
英文:

Laravel : JWT Auth access auth()->user() return null

问题

我正在尝试在我正在构建的API身份验证中使用JWT。我已经成功地使用以下代码获取了JWT令牌:

$user = User::select('id_user', DB::raw('AES_DECRYPT(id_user, "nur") as username'))
    ->where('id_user', DB::raw('AES_ENCRYPT("' . $credentials['username'] . '", "...")'))
    ->where('password', DB::raw('AES_ENCRYPT("' . $credentials['password'] . '", "...")'))
    ->first();

if (!$user) {
    return response()->json(['error' => 'Unauthorized'], 401);
}

$token = auth()->login($user);
if (!$token) {
    auth()->setUser($user);
    return response()->json(['error' => 'Unauthorized'], 401);
}

return $this->respondWithToken($token);

但是,当使用auth()->user()函数获取已登录用户时,它没有返回任何内容:

public function me()
{
    return response()->json(auth()->user());
}

我的返回值是:

{}

这是我的路由设置:

Route::group(['middleware' => 'api', 'prefix' => 'auth'], function ($router) {
    Route::post('login', [AuthController::class, 'login']);
    Route::post('logout', [AuthController::class, 'logout']);
    Route::post('refresh', [AuthController::class, 'refresh']);
    Route::post('me', [AuthController::class, 'me']);
});

以及我的config/auth.php文件:

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

'guards' => [
    // 'web' => [
    //     'driver' => 'session',
    //     'provider' => 'users',
    // ],
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

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

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

我编写的代码是基于此链接中的教程。

我使用Postman进行了测试,并且命令会自动设置环境。我的测试流程如下:

  1. 登录。
  2. 如果令牌成功生成,立即运行测试以执行me()函数。
英文:

I am trying to use JWT for API authentication I am building, I have managed to get the JWT token with code like the following:

$user = User::select('id_user', DB::raw('AES_DECRYPT(id_user, "nur") as username'))
    ->where('id_user', DB::raw('AES_ENCRYPT("' . $credentials['username'] . '", "...")'))
    ->where('password', DB::raw('AES_ENCRYPT("' . $credentials['password'] . '", "...")'))
    ->first();

if (!$user) {
    return response()->json(['error' => 'Unauthorized'], 401);

}

$token = auth()->login($user);
if (!$token) {
    auth()->setUser($user);
    return response()->json(['error' => 'Unauthorized'], 401);
}

return $this->respondWithToken($token);

but when you get a logged in user with the auth()->user() function it doesn't return anything,

public function me( )
{
    return response()->json(auth()->user());
}

my return

{}

this is my routes

Route::group(['middleware' => 'api', 'prefix' => 'auth'], function ($router) {
    Route::post('login', [AuthController::class, 'login']);
    Route::post('logout', [AuthController::class, 'logout']);
    Route::post('refresh', [AuthController::class, 'refresh']);
    Route::post('me', [AuthController::class, 'me']);
});

and my config/auth.php file

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

    'guards' => [
        // 'web' => [
        //     'driver' => 'session',
        //     'provider' => 'users',
        // ],
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

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

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

the code that I wrote based on the tutorial from this link

I did testing using postman, and the command set the environment automatically. My testing flow is as follows.

  1. login,
  2. if the token comes out I immediately run the test to run the me() function

答案1

得分: 1

我想我找到了这个问题的解决办法。laravel 上的 jwt-auth 会将用户的 id 保存到我们创建的负载的子域中。

而根据这条评论,我想,如果我们为 jwt 创建自己的 自定义负载 会怎样。以下是我使用的代码。

$payloadable = [
    "sub" => $user->username,
];

$token = auth()->claims($payloadable)->login($user);

通过这段代码,我们创建了一个子域来存储我的用户 id。

$payload = auth()->payload()->toArray();
$pegawai = Pegawai::select('pegawai.nama', 'pegawai.jbtn')
    ->where('pegawai.nik', $payload['sub'])
    ->first();

这看起来效率不高,但至少对我来说很有用,可以保存我用 AES_ENCRYPT 加密的 id_user 的原始值。

从第一段代码开始,我将我的加密数据解密并存储为用户名列,而原始值(解密结果)则保存在负载中,这样我仍然可以在查询数据库时使用 AES_DENCRYPTAES_ENCRYPT 获取用户数据,因为我的负载中包含我的数据的原始值。

> 我不知道为什么,然而,在 Laravel 中将用 AES_ENCRYPT 加密的数据返回为 JSON 时会返回值 0。

希望这样描述和帮助。

英文:

i think i got the solution for this problem i am facing. where jwt-auth on laravel reads saves the id of our user into the sub in the payload that we created.

and from this comment I thought, what if we make our own custom payload for jwt. here is the code i use.

$payloadable = [
    "sub" => $user->username,
];

$token = auth()->claims($payloadable)->login($user);

with that code we create a sub to store my user id.

$payload = auth()->payload()->toArray();
$pegawai = Pegawai::select('pegawai.nama', 'pegawai.jbtn')
    ->where('pegawai.nik', $payload['sub'])
    ->first();

it does look inefficient, but at least it can be useful for me to save the original value of the id_user that I have encrypted with AES_ENCRYPT.

from the first code I made my encrypted data to be decrypted and stored as a username column, and the original value (the result of decryption) I saved in the paylod, in this way I can still get user data while still using AES_DENCRYPT and AES_ENCRYPT when querying the database, because in the payload that I have contains the original value of my data.

> I don't know why, however, data encrypted with AES_ENCRYPT when returned as json in Laravel returns a value of 0.

I hope that describes and helps

答案2

得分: 0

你在你的控制器中添加了这段代码吗?

public function __construct()
{
  $this->middleware('auth:api', ['except' => ['login']]);
}
英文:

Did you added this code in your controller?

public function __construct()
{
  $this->middleware('auth:api', ['except' => ['login']]);
}

huangapple
  • 本文由 发表于 2023年6月19日 14:10:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定