实现谷歌第三方登录步骤

前言

主要是通过Firebase实现谷歌登录

首先需要有一个谷歌账号登录到Firebase

文档地址https://firebase.google.com/docs/auth/web/google-signin?hl=zh-cn

按照文档上的步骤

第一步吧项目添加到Firebase中

添加成功之后会生成一段代码  放到自己项目的main.js文件中  这样就可以让项目和Firebase建立联系

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
	apiKey: "xxx",
	authDomain: "xxx",
	projectId: "xxx",
	storageBucket: "xxx",
	messagingSenderId: "xxx",
	appId: "xxx",
	measurementId: "xxx"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
// Get a list of cities from your database
async function getCities(db) {
	const citiesCol = collection(db, 'cities');
	const citySnapshot = await getDocs(citiesCol);
	const cityList = citySnapshot.docs.map(doc => doc.data());
	return cityList;
}

第二步

在登录页面引入一下代码

import { getAuth, signInWithPopup, GoogleAuthProvider, } from "firebase/auth";

const auth = getAuth();
const provider = new GoogleAuthProvider();

//点击登录调用这个方法 就会弹出谷歌登录弹出
signInWithPopup(auth, provider)
  .then((result) => {
    // This gives you a Google Access Token. You can use it to access the Google API.
    const credential = GoogleAuthProvider.credentialFromResult(result);

//credential 这个里面会有一个idtoken 我们后端是用这个token获取用户信息

    const token = credential.accessToken;
    // The signed-in user info.
    const user = result.user;
    // IdP data available using getAdditionalUserInfo(result)
    // ...
  }).catch((error) => {
    // Handle Errors here.
    const errorCode = error.code;
    const errorMessage = error.message;
    // The email of the user's account used.
    const email = error.customData.email;
    // The AuthCredential type that was used.
    const credential = GoogleAuthProvider.credentialFromError(error);
    // ...
  });

以上代码文档里面都可以查到

 

注意 !!!  需要再文档里面给自己的网域添加授权才可以实现最终效果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值