laravel使用Google帐户登录 [英] laravel login with google account

查看:463
本文介绍了laravel使用Google帐户登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在申请,我希望用户使用其Google帐户登录.我有oauth-4-laravel用户,我有这个:

I am making an application and I want users to login with their google account. I have user oauth-4-laravel and I have this:

UserController.php

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);
        }
    }

此后,我成功获取了用户信息,并且可以在数据库中保存用户名.问题是在此之后,我想将用户重定向到主页,并且无法执行此操作,因为使用普通登录名时,我会进行身份验证:

After this i get successfully user info and can save user name, in my database. The problem is that after this I want to redirect user to home page and can't do this because with normal login i chec authentication:

if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
            return Response::json(["redirect_to" => "/"]);

并使用Google登录名,获得用户名,用户名和电子邮件. google登录后如何直接登录用户?

and with google login i get onlu username , user id and email. How to login directly the user after google login?

推荐答案

如果您需要将现有的用户实例登录到您的应用程序中,则可以使用该实例简单地调用login方法:

If you need to log an existing user instance into your application, you may simply call the login method with the instance:

$user = User::find(1);

Auth::login($user);

这等效于使用try方法通过凭据登录用户.

This is equivalent to logging in a user via credentials using the attempt method.

有关更多信息,请参见: http://laravel.com/docs/security#manually

For further info see: http://laravel.com/docs/security#manually

这篇关于laravel使用Google帐户登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆