Hi, my project is consisting of two separate apps:
-
Laravel-based back-end
-
An SPA, "living" separately and built using Vue CLI.
Now, I'm trying to implement Login via Facebook.
There are two routes, on the backend:
Route::get('login/{provider}', 'Auth\LoginController@redirectToProvider');
Route::get('login/{provider}/callback', 'Auth\LoginController@handleProviderCallback');
So, if I click a link like: /login/facebook — I'll get logged into Laravel in the result.
Now, I need a way to pass user data to the SPA (which is NOT a part of Laravel). Here's what I've tried so far:
Laravel's Login controller (it's callback action):
// app/Http/Controllers/Auth/LoginController.php
/**
* Obtain the user information from Social provider.
*
* @return \Illuminate\Http\Response
*/
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)
->fields([ 'id', 'name', 'email', 'picture', 'link', 'friends' ])
->user();
session([ 'social_user' => $user ]);
return redirect(config('app.spa_url') . '#authenticated');
}
Then, there is such code in the SPA:
// src/pages/Home/Home.vue
created () {
this.$store.dispatch('loadData')
if (location.hash.indexOf('authenticated') !== -1) {
setTimeout(() => this.$store.dispatch('loadUser'), 1000)
}
},
// src/store.ts
actions: {
loadUser ({ commit, getters }) {
let url = `${getters.backendUrl}/social_user`;
axios.get(url).then(
response => commit('DO_AUTH', response.data.user),
error => // ...
)
}
Finally, here's the code for serving /social_user request in the Laravel:
// routes/web.php
Route::get('social_user', function () {
return response()->json(session('social_user')->user);
});
Note: this is WEB.php, so, the session should be picked up. And it actually does, when I open /social_user URL in the browser. In the Ajax request, however, it's always empty?
So, I have those questions:
-
Why the session variable is empty, but only if it's Ajax request?
-
Are there any other ideas on how to pass user data from laravel to SPA?
One note in regards to #2: authorisation should be handled via redirects (just like Socialite does it). First, I've tried to implement "OAuth Implicit Flow", using popups — but this method didn't work well on mobiles. In particular, popup is not always (no in all browsers/OSes) closed after the access token is retrieved, so, the user thinks the authentication has failed.