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' => AppModelsUser::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.
- login,
- if the token comes out I immediately run the test to run the
me()
function
2
Answers
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.
with that code we create a sub to store my user id.
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 withAES_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
andAES_ENCRYPT
when querying the database, because in the payload that I have contains the original value of my data.I hope that describes and helps
Did you added this code in your controller??