I am trying to authenticate user with api authentication token
. But even after using correct token its saying unauthorized.
I am using laravel auth and socialite for social authentication
so my api.php
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
and in the header
token: TOKEN HERE
Content-Type: application/json
Accept: application/json
I was expecting it to log me in and show the ApiTestController index methord
But its throwing an error 401 unauthorized
How do i fix this issue and get user authenticate using the API token?
My controller
class ApiTestController extends Controller
{
public function index(){
return json_encode ("Welcome REST API");
}
}
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',
],
]
The only thing that i found it can cause the problem is the name of the token
column in the database, it sould be api_token
, so change the migration to this :
$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('api_token', 60)->unique(); //<-- this one here
$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();
Do not forget to refresh the database, and one more thing to get the authenticated user you have to use :
Auth::guard('api')->user()
Instead of :
Auth::user()