Rex Zednelab
Rex Zednelab

Reputation: 37

2 laravel projects communicating using API Sanctum?

I have two laravel projects

I want them to communicate using the Laravel Sanctum API. I want the InfraProject to access some data in the Bac4 project and vice versa.

The Problem

When InfraProject is trying to access the Bac4 using a token, InfraProject is being silly. InfraProject is using its own database to verify the token from the Bac4. Mind you that the Token is in the database of Bac4. I can't seem to find the problem why the InfraProject is using it's own database to verify the token from another database.

I came to this conclusion that the InfraProject is accessing its own database is because i have tried to use a login API

Bac4

Route::post('/login', function (Request $request) {
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if (!Auth::attempt($credentials)) {
        return response()->json(['message' => 'Invalid credentials'], 401);
    }

    $user = Auth::user();
    $token = $user->createToken('API Token')->plainTextToken;

    return response()->json([
        'user' => $user,
        'token' => $token,
    ]);
});

InfraProject The credentials are definitely in the bac4 database.

$response = Http::post('http://bac4.test/api/login', [
    'email' => 'ba****[email protected]',
    'password' => '******',
]);

$token = $response->json('token');
dd($token, $response);

but when i use a credential from the InfraProject's database. It produced a Token.

What i have tried I have tried to remove the middleware auth:sanctum which i have declared in Bac4. Route::get('prs', [PrController::class, 'index']); But the InfraProject is, again, using its own database to access the prs table.

I ensured that both projects has \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class in the kernel in api array.

I also ensure that all affected models has a $connection specified.

ChatGpt can't figure the root cause of this, so this is my last chance.

I hope that you can help me.

Upvotes: 0

Views: 95

Answers (1)

user28998819
user28998819

Reputation:

I implemented similar thing by using laravel-crud-wizard-free coupled with sanctum for authorizing the requests and I did not had this issue. Leave AI out of your coding habit and you will be better.

I suggest you check the laravel https://laravel.com/docs/11.x/sanctum#api-token-authentication documentation on how to use sanctum + make sure each project has its own DB schema.

Upvotes: 0

Related Questions