The issue stemmed from both applications being local. When I moved application B to a real server, the problem disappeared. Just for your information, I'm using Laragon. Hopefully, this will help others.
Jun 15, 2024
1
Level 1
API Authentication between 2 Laravel 10 Applications
I have two Laravel 10 applications, called A and B. The user is using application A and needs to authenticate via an API of application B to obtain a token. The problem is that the authentication on the API of B always fails when it is done from A. However, when I test the API of B with Postman, it correctly returns a token.
Here is the controller method from A :
public function getToken()
{
$response = Http::withHeaders([
'content-type' => 'application/json; charset=utf-8',
'accept' => '*/*',
'accept-encoding' => 'gzip,deflate',
'connection' => 'close'
])->post('http_B_address', [ //I removed the address of B because it was not allowed when I wrote this message.
'email' => '[email protected]',
'password' => 'xyz'
]);
if ($response->successful()) {
$data = $response->json();
dd($data);
} else {
$error = $response->body();
dd($error);
}
}
And the code for B that works well when I test with Postman (routes/api.php) :
Route::post('/token', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) { //Always returns false when I use A and returns true when I use Postman
$token = $user->createToken('API Token')->plainTextToken;
return response()->json(['token' => $token]);
} else {
return response()->json(['message' => 'Unauthorized'], 401);
}
});
Have I forgotten something in A? Or do you have any suggestions for me? Thank you for your help.
Level 1
Please or to participate in this conversation.