[英]Laravel 5 Social authentification (Facebook)
我有一些我無法使用Laravel官方文檔回答的問題。我正在嘗試使用這種隨處可見的實用Facebook(或其他SNS)登錄名。
我尋找了一本很好的教程,但沒有比這更好的了。
我遵循了它,我想我幾乎了解這里涉及的過程。
但是那又怎樣呢? 我們如何訪問我們網站的受保護部分? 我的意思是我們如何通過現成的中間件傳遞已經擁有的中間件?
因為我在標准登錄頁面(www.mywebsite / auth / login)上有我的FB登錄按鈕,但是我不太了解我的service.php中應該有什么回調?
目前
'facebook' => [
'client_id' => '12321452415',
'client_secret' => '675f2d7f77232b0fb20762261db6dcd072',
'redirect' => 'http://mywebsite/',
],
但是當然,如果我調用主頁,由於中間件的原因,我剛剛又被重定向到了登錄頁面。 我是說我做錯了還是做得不夠?
希望我足夠清楚..
任何幫助非常感謝
您在services.php下定義的重定向應該是您網站的路由,例如http://website.com/callback ; 在Facebook上驗證您的請求后,您將被重定向回該路線。 如果您在沒有任何額外權限的情況下使用基本的Facebook應用程序,那么您將獲得用戶的Facebook名稱,fb個人資料ID,照片以及您所引用的教程中提及的一些其他詳細信息。 您可以利用這些詳細信息在您的網站上對用戶進行身份驗證,例如,您有一個表用戶,其中有一個額外的列,即fb_id。一旦從Facebook獲得響應,就檢查數據庫,如果從響應中獲得的fb_id是否存在於數據庫中? 如果是,則使用
Auth::loginUsingId($fetched->id);
{
return redirect()->to('some-route');
}
如果沒有得到與此fb_id匹配的記錄,則在數據庫中插入一條新記錄,然后loginUsingId
我希望我對此足夠清楚。
好吧,我敢肯定我可以做得更好,但是我有一些工作(在撓了一下頭之后)
我的路線:
Route::get('connect/{provider}', 'AccountController@redirectToProvider');
Route::get('account/{provider}', 'AccountController@handleProviderCallback');
而我的控制器:
class AccountController extends Controller {
public function redirectToProvider($provider) {
return Socialize::with($provider)->redirect();
}
public function handleProviderCallback($provider) {
$user = Socialize::with($provider)->user();
// Define the SNS variable
$id = $user->getId();
$name = $user->getName();
$email = $user->getEmail();
$avatar = $user->getAvatar();
// check if the user exists in the DB already
$users = DB::table('users')->where($provider.'_id', $id)->first();
// if the user doesn't exist insert a new record and get the user_id
if(empty($users)){
DB::table('users')->insert(
['name' => $name,'email' => $email,'profile_picture' => $avatar,$provider.'_id' => $id]
);
$users = DB::table('users')->where($provider.'_id', $id)->first();
}
// use the auth facade to login with the user ID
Auth::loginUsingId($users->id);
{
// redirect to the home page
return redirect()->to('/');
}
}
}
我的登錄頁面:
<a href="{!!URL::to('connect/facebook')!!}">Login with Facebook</a><br>
<a href="{!!URL::to('connect/twitter')!!}">Login with Twitter</a><br>
<a href="{!!URL::to('connect/google')!!}">Login with Google</a>
任何改進都歡迎。 我知道這並不完美,但可能會幫助某人:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.