Search code examples
laravelauthenticationlaravel-passportlaravel-socialite

How to create REST API with socialite and passport in laravel


I want to create REST API which will use social (google) login system to authenticate the user into the system .

I am using laravel auth and socialite for social authentication so my route is like this

Route::group(['middleware'=>'auth:api'], function(){
  Route::get('hello','ApiTestControler@index');
});

And i m trying to access this with this url

http://localhost:8000/api/hello?token=16Wf313JyO66cgXk6UstxsIzrf0hlt8tsP09i04UczkWysHWoveVcHGhUPz6YTdX

I was expecting it to log me in and show the ApiTestController index methord

But its showing me login page. How do i fix this issue and get user authenticate using the API token?

UPDATE

User migration table

        $table->increments('id');
        $table->string('name')->unique();
        $table->string('first_name')->nullable();
        $table->string('last_name')->nullable();
        $table->string('email')->unique()->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->boolean('activated')->default(false);
        $table->string('token');
        $table->ipAddress('signup_ip_address')->nullable();
        $table->ipAddress('signup_confirmation_ip_address')->nullable();
        $table->ipAddress('signup_sm_ip_address')->nullable();
        $table->ipAddress('admin_ip_address')->nullable();
        $table->ipAddress('updated_ip_address')->nullable();
        $table->ipAddress('deleted_ip_address')->nullable();
        $table->timestamps();
        $table->softDeletes();

And the auth configuration in config\auth.php

'guards' => [
        'web' => [
            'driver'   => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver'   => 'token',
            'provider' => 'users',
        ],
      ]

Solution

  • The issue here is that Laravel does not know that this is an api call, it thinks that its a web call. So to fix this you need to add application/json on your headers :

    Content-Type: application/json
    
    Accept: application/json
    

    As soon as you add json on your headers and make a call then laravel will know that is an api call! Therfore it will load your api controller.