Google(OAuth2.0)PHP 授权登录

来源:csdn博客 分类: 文章浏览史 发布时间:2020-08-26 19:30:47 最后更新:2020-08-26 浏览:5593
转载声明:
本文为摘录自“csdn博客”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2020-08-26 19:30:47

OAuth协议

OAuth(开放授权)是一个开放标准。
允许第三方网站在用户授权的前提下访问在用户在服务商那里存储的各种信息。
而这种授权无需将用户提供用户名和密码提供给该第三方网站。
OAuth允许用户提供一个令牌给第三方网站,一个令牌对应一个特定的第三方网站,同时该令牌只能在特定的时间内访问特定的资源。

OAuth的原理和授权流程

OAuth的认证和授权的过程中涉及的三方包括:
服务商:用户使用服务的提供方,一般用来存消息、储照片、视频、联系人、文件等(比如Twitter、Sina微波等)。
用 户:服务商的用户
第三方:通常是网站,该网站想要访问用户存储在服务商那里的信息。
比如某个提供照片打印服务的网站,用户想在那里打印自己存在服务商那里的网络相册。
在认证过程之前,第三方需要先向服务商申请第三方服务的唯一标识。
OAuth认证和授权的过程如下:
1、用户访问第三方网站网站,想对用户存放在服务商的某些资源进行操作。
2、第三方网站向服务商请求一个临时令牌。
3、服务商验证第三方网站的身份后,授予一个临时令牌。
4、第三方网站获得临时令牌后,将用户导向至服务商的授权页面请求用户授权,然后这个过程中将临时令牌和第三方网站的返回地址发送给服务商。
5、用户在服务商的授权页面上输入自己的用户名和密码,授权第三方网站访问所相应的资源。
6、授权成功后,服务商将用户导向第三方网站的返回地址。
7、第三方网站根据临时令牌从服务商那里获取访问令牌。
8、服务商根据令牌和用户的授权情况授予第三方网站访问令牌。
9、第三方网站使用获取到的访问令牌访问存放在服务商的对应的用户资源。

一、创建新的项目,获取 ClientID 和 Secret

https://console.developers.google.com

1.在谷歌平台申请自己的账号,创建新的项目
1创建新的项目

2.添加网页应用信息
添加网页应用信息ybaog

3.创建凭据
创建凭据ybaog

4.创建网页应用,填写回调地址
创建网页应用ybaog

5.应用创建成功
应用创建成功ybaog

6.查看客户端 ID和客户端密钥
查看客户端详情ybaog

二、部署代码

<?php
header('Content-Type:text/html; charset=utf-8');
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/14
 * Time: 16:15
 */
class Google
{
    protected $setting = [
        'app_id' => 'skdjfkdj56.apps.googleusercontent.com',  //客户端ID
        'redirect_uri' => 'http://www.ybaog.com/back.php',     //回调地址
        'app_secret' => 'sudifjfiflkasifjafma658',             //客户端密钥
    ];

    public function __construct()
    {
        $this->client_id = $this->setting['app_id'];
        $this->client_secret = $this->setting['app_secret'];
        $this->redirect_uri = $this->setting['redirect_uri'];
    }

    function index(){

        //第一步:请求CODE
        if (empty($_GET['code'])) {
            $this->getCode($this->client_id,$this->redirect_uri);
        } else {

            //用户允许授权后,将会重定向到redirect_uri的网址上,并且带上code参数
            $code=$_GET['code'];
            $postData=array(
                'code'=>$code,
                'client_id'=>$this->client_id,
                'client_secret'=>$this->client_secret,
                'redirect_uri'=>$this->redirect_uri,
                'grant_type'=>'authorization_code'
            );

            //第二步:通过code获取access_token
            $access_token=$this->getToken($postData);
            if(empty($token)){
                die( "<center><h2 style='color: red'>获取TOKEN失败!</h2></center>");
            }

            //第三步:通过access_token调用接口,获取用户信息
            $user=$this->getUserInfo($access_token);

            //处理获取到的的用户数据。。。。。。

        }
    }

    /**
     * 抓取CODE
     * @param $client_id
     * @param $redirect_uris
     */
    protected function getCode($client_id,$redirect_uris){
        $redirect_uris=urlencode($redirect_uris);
        $scope=urlencode('https://www.googleapis.com/auth/userinfo.profile');
        $url = "https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id={$client_id}&redirect_uri={$redirect_uris}&state&scope={$scope}&approval_prompt=auto";
        header('Location:' . $url);
    }


    /**
     * 抓取TOKEN
     * @param $postData
     * @param string $purl
     * @return bool
     */
    protected function getToken($postData,$purl='https://accounts.google.com/o/oauth2/token'){

        $fields = (is_array($postData)) ? http_build_query($postData) : $postData;
        $curlHeaders = [
            'content-type: application/x-www-form-urlencoded;CHARSET=utf-8',
            'Content-Length: ' . strlen($fields),
        ];

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $purl);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($curl);
        $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if($response && $responseCode == 200){

            $json = json_decode($response, true);
            $token=$json['access_token'];
            return $token;
        }else {
            return false;
        }

    }

    /**
     * 获取用户信息
     * @param $access_token
     * @return array
     */
    protected function getUserInfo($access_token){
        $url = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=".$access_token;
        $userInfo = json_decode(file_get_contents($url),true);

        $data['id']=$userInfo['id'];                     //ID
        $data['name']=$userInfo['name'];                //用户名
        $data['locale']=$userInfo['locale'];           //语言
        $data['picture']=$userInfo['picture'];         //头像
        $data['given_name']=$userInfo['given_name'];   //名字
        $data['family_name']=$userInfo['family_name']; //姓

        return $data;
    }

}

$google=new Google;
$result=$google->index();

希望可以帮到你!!!

1楼 mzq
2023-01-17 22:52:00
114514
php技术微信