我有一个基于Angular 6的前端SPA和基于Laravel 5.6的后端SPA。我正在尝试使用前端的ngx-social-login
和后端的Socialite
进行Facebook身份验证。
那是我组件中的代码
signInWithFacebook(): void {
this.sas.signIn(FacebookLoginProvider.PROVIDER_ID).then(
userData => this.as.fb(userData.authToken).subscribe(x => {
console.log(x);
})
);
}
这是一项服务
fb(data): Observable<any> {
return this.http.get(this.API_URL, data);
}
这是我的Laravel路线
$api->version('v1', function ($api) {
$api->get('auth/facebook', 'SocialAuthFacebookController@redirectToProvider');
$api->get('auth/facebook/callback', 'SocialAuthFacebookController@callback');
});
那是控制器
public function redirectToProvider()
{
return Socialite::driver('facebook')->stateless()->redirect();
}
public function callback()
{
$user = Socialite::driver('facebook')->stateless()->user();
$authUser = $this->findOrCreateUser($user, 'facebook');
$token = JWTAuth::fromUser($authUser);
return Response::json(compact('token'));
}
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => $provider,
'provider_id' => $user->id
]);
}
由于我将Laravel用作仅API,所以我想我无法访问redirectToProvider
,因此我尝试调用auth/facebook/callback
并将其传递给我之后得到的authToken
在我的SPA上登录。但是,它似乎不起作用。
由于Facebook有太多信息,所以我不知道出了什么问题以及如何处理。
答案 0 :(得分:0)
以下示例可能会有所帮助:
/** * Redirect the user to the Facebook authentication page. * * @return Response */ public function redirectToProvider() { return Socialite::driver('facebook')->stateless()->redirect(); } /** * Obtain the user information from Facebook. * * @return JsonResponse */ public function handleProviderCallback() { $providerUser = Socialite::driver('facebook')->stateless()->user(); $user = User::query()->firstOrNew(['email' => $providerUser->getEmail()]); if (!$user->exists) { $user->name = $providerUser->getName(); $user->save(); } $token = JWTAuth::fromUser($user); return new JsonResponse([ 'token' => $token ]); }