I'm having a problem trying to authenticate api with the attemp()
function in laravel, because I need to run the AES_ENCRYPT
function in mysql to be able to match my post data with the data in the database. this is the code i wrote in the controller i have
$user = User::select('*',DB::raw("AES_DECRYPT(id_user, '...') as username, AES_DECRYPT(password, '...') as passwd"))
->where('id_user', DB::raw("AES_ENCRYPT('" . $id_user . "', '...')"))
->where('password', DB::raw("AES_ENCRYPT('" . $password . "', '...')"))
->first();
$encryptedIdUser = DB::table('user')->selectRaw("AES_ENCRYPT('" . $id_user . "', 'nur') as id_user")->first();
$encryptedPassword = DB::table('user')->selectRaw("AES_ENCRYPT('" . $password . "', 'windi') as password")->first();
if ($user) {
if (!$token = Auth::guard('api')->attempt([
"id_user" => $encryptedIdUser->id_user,
"password" => $encryptedPassword->password,
])) {
return response()->json([
'success' => false,
'message' => 'Authentication failed!',
], 401);
}
} else {
return response()->json([
'success' => false,
'message' => "Username or password is incorrect or user doesn't exist",
], 401);
}
return response()->json([
'success' => true,
'message' => 'Authentication success!',
'token' => $token,
], 200);
from the code above I always get authentication failed, is there something wrong, can you help me. ?
the token is required to get the token from JWT
here is the code that I wrote in my model
and config/auth.php
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users_api' => [
// 'driver' => 'database',
// 'table' => 'user',
// ],
],
user.php (model)
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable;
protected $table = 'user';
protected $primaryKey = 'id_user';
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}