Hmmm, I think you should just be able to login the user in Laravel after a successful registration or social login and not deal with creating tokens manually. The token necessary to make further requests to the API can be added automatically by Passport, take a look at https://laravel.com/docs/5.8/passport#consuming-your-api-with-javascript
Adding Social Authentication to API
Guys, I am working on an API application using Laravel 5.8. The API application has no web page and will only be returning json response. For instance when a user is successfully authenticated, a response is returned similar to this
{
"responseMessage":"Successfully Registered.",
"responseStatus":201,
"token":"eyJ0eXAiOiJKV1...",
}
To add social authentication, I have added the socialite package and was able to log new users in using facebook and google with this code blocks below
Redirect and Callback routes in web.php file
Auth::routes(['verify' => true]);
Route::get('/auth/{provider}', 'SocialAuthController@redirectToProvider');
Route::get('/auth/{provider}/callback', 'SocialAuthController@handleProviderCallback');
Then the controller methods are
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
// retrieve social user info
$socialUser = Socialite::driver($provider)->stateless()->user();
// check if social user provider record is stored
$userSocialAccount = SocialAccount::where('provider_id', $socialUser->id)->where('provider_name', $provider)->first();
if ($userSocialAccount) {
// retrieve the user from users store
$user = User::find($userSocialAccount->user_id);
// assign access token to user
$token = $user->createToken('string')->accessToken;
// return access token & user data
return response()->json([
'token' => $token,
'user' => (new UserResource($user))
]);
} else {
// store the new user record
$user = User::create([...]);
// store user social provider info
if ($user) {
SocialAccount::create([...]);
}
// assign passport token to user
$token = $user->createToken('string')->accessToken;
$newUser = new UserResource($user);
$responseMessage = 'Successfully Registered.';
$responseStatus = 201;
// return response
return response()->json([
'responseMessage' => $responseMessage,
'responseStatus' => $responseStatus,
'token' => $token,
'user' => $newUser
]);
}
}
Now when a user is authenticated, I see the expected message in the web browser window (not console). Can the the react web application or mobile application use the information that is returned this way? Or is there another way of doing it? I am not sure as this is my first implementation of implementing social auth to API only application.
Please or to participate in this conversation.