实现谷歌第三方登录步骤
前言
主要是通过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);
// ...
});
以上代码文档里面都可以查到