admin管理员组文章数量:1530518
调用Google官方API,使用Google账号登录个人搭建的网站。
一、配置工作
1.参考《两种方式使用Gmail发送邮件:OAuth2.0或应用专用密码》先后创建Project、OAuth同意屏幕以及OAuth 2.0 Client ID,但Client的应用类型选择Web application
2.在Authorized JavaScript origins添加两个URI: http://localhost 和 http://localhost:7777
注: 生产环境中需要添加https协议的真实域名以及端口号,如需Authorized redirect URIs自行添加。
3.后续开发Web应用只需要用到这个Client的ID
二、示例教程
1.配置环境: 基于Python3.8创建一个虚拟环境并安装以下依赖
pip install flask==3.0.2
2.编写index.html: 将html放在templates文件夹下,并将其中的client_id修改为真实的ID
<!DOCTYPE html>
<html>
<head>
<title>WEB</title>
<script src="https://accounts.google/gsi/client" async></script>
</head>
<body>
<span id="blank_zone" style="display: flex; justify-content: center; align-items: center; height: 25vh;"></span>
<span id="prompt" style="display: flex; justify-content: center; align-items: center;">
Please sign in with Google:
</span>
<br/>
<div id="login_zone" style="display: flex; justify-content: center; align-items: center;">
<div id="g_id_onload"
data-client_id="client_id"
data-context="signin"
data-ux_mode="popup"
data-auto_prompt="false"
data-callback="onLoginCallback">
</div>
<div class="g_id_signin"
data-type="standard"
data-shape="pill"
data-theme="filled_blue"
data-text="signin_with"
data-size="large"
data-logo_alignment="left">
</div>
</div>
<span id="user_info" style="display: flex; justify-content: center; white-space: pre-line;"></span>
<script>
function onLoginCallback(response) {
var credential = response.credential,
sub_credential = credential.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"),
profile = JSON.parse(decodeURIComponent(escape(window.atob(sub_credential)))),
target = document.getElementById("user_info"),
html = "";
html += "ID: " + profile.sub + "\n";
html += "Name: " + profile.name + "\n";
html += "Email: " + profile.email + "\n";
target.innerHTML = html;
document.getElementById("prompt").style.display = "none";
document.getElementById("login_zone").style.display = "none";
}
</script>
</body>
</html>
3.编写Web示例app.py: 应用以debug模式运行在本地的7777端口,端口号与Google中配置的一致
# -*- coding: utf-8 -*-
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/", methods=["GET"])
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(host="localhost", port=7777, debug=True)
4.运行Web示例应用,即可使用Google账号登录网站
注: 生产环境中需要自行实现代码逻辑,使用Google的credential来认证用户并管理用户会话的生命周期。
版权声明:本文标题:使用Google账号登录个人网站 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1725992064a1051614.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论