Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I login manually with API between two laravel project?

Tags:

php

laravel

I have two Laravel project, I want to login with the API that the first project provides and use this authentication in the second project.

in the LoginController in second project:


public function login(Request $request)
    {
        $login_response = Http::post('{first_project_login_api}', [
            'data' => [
                "email"     => $request->input('email'),
                "password"  => $request->input('password')
            ]
        ]);

        if ($this->attemptLogin($login_response)) {
            return $this->sendLoginResponse($request);
        }
    }

protected function attemptLogin(Response $response)
    {
        return $response->object()->status === 200;
    }

In the second project, I don't need database because I want to do authentication in the first project, but that doesn't seem to be possible!

actually I need to know how to overwrite attemptLogin() function in LoginController.

It would be highly appreciated if anyone can advise me!

like image 746
Nothehi Avatar asked Dec 30 '25 03:12

Nothehi


1 Answers

Instead of using login between application, i would use API keys. The easiest way to get started is to use simple API Authentication.

First create migrations for the user table.

Schema::table('users', function ($table) {
    $table->string('api_token', 80)->after('password')
        ->unique()
        ->nullable()
        ->default(null);
});

To get keys, set them on the user either in Tinker, command or creation.

$user->api_token = Str::random(60);
$user->save();

Protect your API routes with a middleware.

Route::middleware('auth:api')->group(function() {
    // your routes
});

Calling your api is as simply as.

response = $client->request('POST', $yourRoute, [
    'headers' => [
        'Authorization' => 'Bearer ' . $yourToken,
        'Accept' => 'application/json',
    ],
]);

This is a fairly basic setup, for production or moving forward you should look into Sanctum or Passport. This is just a good start, from where i feel you are based on your question.

like image 73
mrhn Avatar answered Jan 01 '26 20:01

mrhn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!