前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

谷歌web授权登陆(PHP)(谷歌登录授权失败怎么回事啊)

qiguaw 2024-10-29 15:29:25 资源文章 21 ℃ 0 评论

前言

在当今数字化时代,保护用户数据和提供安全的身份验证方式至关重要。谷歌 Web 授权登录是一种流行的身份验证方法,它提供了简单、方便和安全的用户身份验证方式。本文将介绍如何使用 PHP 实现谷歌 Web 授权登录,让你的网站或应用程序获得可靠的用户认证功能。 在现代网络应用程序中,用户身份验证是至关重要的一部分。为了保护用户的数据和隐私,开发人员需要使用安全可靠的身份验证机制。谷歌 Web 授权登录提供了一种简单而有效的方式来实现用户身份验证,同时还提供了额外的安全保障,例如双因素身份验证和访问令牌管理。

准备

  • 注册谷歌开发者账号。
  • 创建 OAuth 2.0 客户端 ID。 需要配置回调地址,供后端处理
  • 配置 OAuth 同意屏幕。

前端代码

//只贴了部分代码
<view class="google-container">
   <view class="google-content">
<text class="margin-bottom-sm">-Outros metodos de inicio de sessao-/text>
<!--<image src="../../static/cons/google.png"mode="widthFix"style="width:40px;"id="buttonDiv"></image>-->
<div id="g id_onload" data-client_id="" :data-context="'signin'"
data-ux_mode="'popup'"
data-login uri="url?pid='+pid"
data-auto_prompt="'false'">
</div>

//data-client_id谷歌凭证那额复制 url自己配置,后面可以携带参数
<div class="g_id_signin"
data-type="'icon'"
data-shape="'circle'"
data-theme="'filled blue'"
data-text="'signin with'"
data-size="'large'">
</div>
</view>
</view>
</view>

引用的js
mounted(){
/动态动加载Google登录脚本
const script document.createElement('script');
script.src 'https://accounts.google.com/gsi/client';
script.async true;
/script.onload this.initializeGoogleSignIn;
document.head.appendChild(script);
}

效果图

image

后端代码

php有引用两个composer包

composer require google/apiclient firebase/php-jwt
 public function google()
    {
        $param = $this->request->param();
        trace($param, 'error');
        $jwksUrl = 'https://www.googleapis.com/oauth2/v3/certs';
        // 获取谷歌的公钥
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $jwksUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        if ($response) {
            $jwks = json_decode($response, true);
            // 解码和验证 JWT
            try {
                $decoded = JwT::decode($param['credential'], JWK::parseKeySet($jwks), ['RS256']);
                $json = json_encode($decoded);
                // 获取用户信息
                $email = $decoded->email;
                $name = $decoded->name;
                $picture = $decoded->picture;
           
                // 在这里处理用户信息,例如登录或注册用户
            } catch (Exception $e) {
                echo '验证令牌失败: ',  $e->getMessage(), "\n";
            }
        } else {
            echo '无法获取谷歌公钥';
        }
    }

以上代码仅供参考。如遇版本更新,可能有所不同。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表