问题描述
我有一些问题无法通过 Laravel官方文档来回答 ..我正在尝试使用我们到处都能看到的这种实用的Facebook(或其他SNS)登录名.
I have a few questions that I can't answer with the Laravel official doc.. I am trying to use this practical Facebook (or other SNS) login that we see everywhere.
我一直在寻找关于它的好教程,但找不到比那个.
I had looked for a good tutorial about it but I couldn't find better than that one.
我遵循了它,我认为我非常了解这里涉及的过程.
I followed it and I think I pretty much understand the process involved in here.
- 我们的网站转到FB
- 我们在FB上进行身份验证
- 然后,我们被重定向回我们的应用程序.带有保存在某处的令牌"和用户数据.
那又如何呢?我们如何访问我们网站的受保护部分?我的意思是我们如何通过现成的中间件传递已经拥有的中间件?
But then what ? How do we access the protected part of our website ? I mean how do we pass the, out of the box middleware, that we already have ?
因为我在标准登录页面(www.mywebsite/auth/login)上有我的FB登录按钮,但是我不太了解的是service.php中应该有什么回调?
Because I have my FB login button on the standard login page (www.mywebsite/auth/login) but then what I don't quite understand is what callback in my service.php should I have ?
当前
'facebook' => [
'client_id' => '12321452415',
'client_secret' => '675f2d7f77232b0fb20762261db6dcd072',
'redirect' => 'http://mywebsite/',
],
但是,当然,如果我调用主页,由于中间件的原因,我刚刚又被重定向到我的登录页面.我是说我做错了还是做得不够?
But off course if I call my main page I just got redirected to my login page again because of the middleware.. right ?? I mean did I do something wrong or I just didn't do enough ?
希望我足够清楚..
非常感谢任何帮助
推荐答案
好吧,我敢肯定我可以做得更好,但是我有一些工作(在挠了一下头之后)
Ok, I am sure I can do much better than that but I have something working (after scratching my head a couple of time)
我的路线:
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>
欢迎任何改进.我知道这并不完美,但可能会帮助某人:)
Any improvements is welcomed.I know it's not perfect but it might help someone :)
这篇关于Laravel 5社会认证(Facebook)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!