我正在制作一个应用程序,我希望用户使用他们的 Google 帐户登录。我有用户 oauth-4-laravel 并且我有这个:
UserController.php
// get data from input
$code = Input::get('code');
// get google service
$googleService = Artdarek\OAuth\Facade\OAuth::consumer("Google");
if (!empty($code)) {
// This was a callback request from google, get the token
$token = $googleService->requestAccessToken($code);
// Send a request with it
$result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
$user = DB::select('select id from users where email = ?', array($result['email']));
if (empty($user)) {
$data = new User;
$data->Username = $result['name'];
$data->email = $result['email'];
$data->first_name = $result['given_name'];
$data->last_name = $result['family_name'];
$data->save();
}
if (Auth::attempt(array('email' => $result['email']))) {
return Redirect::to('/');
} else {
echo 'error';
}
}
// if not ask for permission first
else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to facebook login url
return Redirect::to((string) $url);
}
}
此后,我成功获取用户信息并可以将用户名保存在我的数据库中。问题是,在此之后我想将用户重定向到主页,但无法执行此操作,因为正常登录时我会检查身份验证:
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
通过谷歌登录,我可以获得用户名、用户 ID 和电子邮件。 google登录后如何直接登录用户?
最佳答案
如果您需要将现有用户实例登录到您的应用程序中,您可以简单地使用该实例调用登录方法:
$user = User::find(1);
Auth::login($user);
这相当于使用尝试方法通过凭据登录用户。
有关更多信息,请参阅:http://laravel.com/docs/security#manually
关于laravel 使用 google 帐户登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23802969/