I have a problem with laravel 8 and jwt token here is a little background I have two laravel 8 api with two databases on two different servers which I will call app 1 and app 2 and I must be able to auto connect with user 1 who has id 5 on app 1 and this same user exists but he has id 2 on app 2 but the reverse is not possible a user of app 2 cannot this connect to app 1 so sso is not possible unless I'm wrong? . The problem is that laravel, but automatically id of the current user id 5 in the subject 'sub' of the token and I cannot overload this when I would have to give it id 2 in the ' sub 'of the token, I manage to customize the token by adding email for example and I get the id of user 2 in the database of app 2, but each time laravel pass id of user 1, would anyone have an idea
Here is my code here at the login I will look in the DB for the user according to his email which is unique and I put in session the information that I retrieve and launch the autoload function which creates a new token
$app2User = DB::connection('mysql2')->table("users")->where('email', '=', $request->email)->pluck('id');
if (count($app2User) > 0) {
session(['app2UserId' => $app2User[0], 'app2UserEmail' => $request->email]);
$this->autoload();
} else {
log::info('is null');
}
session(['optisiloUserEmail' => $request->email]);
return $this->createNewToken($token);
Autoload function in which I put the token create in app2UserToken session to transmit it to my createNewToken function which sends me a json with the token of the current user and access_token to send to app2 for this connection
public function autoload()
{
$id = session('optisiloUserId');
$email = session('optisiloUserEmail');
$payload = JWTFactory::sub($id)->email($email)->make();
$token = JWTAuth::encode($payload);
session(['app2UserToken' => $token->get()]);
}
protected function createNewToken($token)
{
return response()->json([
'token' => $token,
'access_token' => session('optisiloUserToken'),
'token_type' => 'bearer',
'expires_in' => Auth::factory()->getTTL() * 60,
'user' => User::where('id', Auth::id())
]);
}
}
I tried this in the User model but suddenly it works on app 2 but no longer on app1 because the sub takes user id from app 2 it is the function $this->getKey() which retrieves the primaryKey or id of the current user
public function getJWTIdentifier()
{
$id = $this->getKey();
$res = User::where('id', $id)->pluck('id_user_app2')[0];
if ($res === null) {
return $this->getKey();
} else {
return $res;
}
}
how could we override the token's sub or or tell it who puts id 5 in the token and id 2 in access_token?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community