Inq*_*Tom 7 javascript firebase google-api-js-client reactjs
如何让 Firebase Auth 与 Google Drive api 配合使用?
使用 React,我的 firebase auth 工作和 googledrive(gapi)都可以单独工作,但正在努力将两者合并。
借助 Firebase 9,访问 Google API 变得更加容易:This gives you a Google Access Token. You can use it to access Google APIs.
我的想法是获取令牌,然后将其传递给gapi.init
函数。然而,我不知道之后该去哪里。任何正确方向的指导将不胜感激!
import { getAuth, getRedirectResult, GoogleAuthProvider } from "firebase/auth";
onst auth = getAuth();
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);
const token = credential.accessToken;
Run Code Online (Sandbox Code Playgroud)
我的gapi实现:
useEffect(() => {
window.gapi.load("client:auth2", initClient);
}, []);
useEffect(() => {
if (authState) {
authState.isSignedIn.listen(updateSigninStatus);
}
}, [authState]);
const initClient = () => {
try {
window.gapi.auth2
.init({
apiKey: "API KEY...",
clientId:
"CLIENT ID...",
scope: "https://www.googleapis.com/auth/drive",
discoveryDocs: [
"https://www.googleapis.com/discovery/v1/apis/drive/v3/rest",
],
})
.then(() => {
const authInstance = window.gapi.auth2.getAuthInstance();
setAuthState(authInstance);
});
} catch (err) {
console.log(err);
}
};
const signInFunction = () => {
authState.signIn();
updateSigninStatus();
};
const signOutFunction = () => {
authState.signOut();
};
const updateSigninStatus = () => {
setSigninStatus();
};
const setSigninStatus = async () => {
//code...
}
}
};
Run Code Online (Sandbox Code Playgroud)
小智 2
我正在为同样的事情而苦苦挣扎,然后我听到 Fireship 人员谈论相反的做法是多么容易 - 使用gapi 登录并将凭据传递给 Firebase。
我将分享我的做法,以便您可以了解该解决方案并将其应用到您的项目中。
使用文件中的gapi-script启动gapigapi.js
并导出将在整个应用程序中使用的gapi 实例。
import { gapi } from 'gapi-script'
gapi.load('client:auth2', async () => {
gapi.client.init({
apiKey: <YOUR_API_KEY>,
clientId: <YOUR_GAPI_CLIENT_ID>,
scope: 'https://www.googleapis.com/auth/drive.metadata.readonly',
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
})
gapi.client.load('drive', 'v3', () => {})
})
export default gapi
Run Code Online (Sandbox Code Playgroud)
然后在单独的文件中启动 Firebase,如下所示:
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: <YOUR_FIREBASE_API_KEY>,
authDomain: <YOUR_FIREBASE_AUTH_DOMAIN>,
projectId: <YOUR_FIREBASE_PROJECT_ID>,
storageBucket: <YOUR_FIREBASE_STORAGE_BUCKET>,
messagingSenderId: <YOUR_FIREBASE_MESSAGING_SENDER_ID>,
appId: <YOUR_FIREBASE_APP_ID>,
clientId: <YOUR_FIREBASE_CLIENT_ID>,
scopes: ['email', 'profile', 'https://www.googleapis.com/auth/drive.metadata.readonly'],
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
}
const firebaseApp = initializeApp(firebaseConfig)
const firebaseAuth = getAuth(firebaseApp)
export { firebaseApp, firebaseAuth }
Run Code Online (Sandbox Code Playgroud)
最后,在该auth.js
文件中,您可以定义将在整个项目中使用的函数。您会注意到,登录后id_token
会从身份验证响应中获取并作为凭证传递给GoogleAuthProvider
.
import { GoogleAuthProvider, signOut, signInWithCredential } from 'firebase/auth'
import { firebaseAuth } from './firebaseConfig'
import gapi from '../gapi'
/**
* Sign in using gapi and pass credential to Firebase
* Needs to be configured in https://console.firebase.google.com/u/0/project/<YOUR_PROJECT>/authentication/providers
* by passing Web SDK Configuration (Web client ID and Web client secret) which can be found on
* https://console.cloud.google.com/apis/credentials?project=<YOUR_PROJECT> under OAuth 2.0 Client IDs
*/
const signInPopup = async () => {
try {
const googleAuth = gapi.auth2.getAuthInstance()
const googleUser = await googleAuth.signIn()
const token = googleUser.getAuthResponse().id_token
const credential = GoogleAuthProvider.credential(token)
const response = await signInWithCredential(firebaseAuth, credential)
// store user
} catch (error) {
// clean user from store
console.error('signInPopup (firebase/auth.js)', error)
}
}
const signOutUser = async () => {
try {
await gapi.auth2.getAuthInstance().signOut()
console.log('User is signed out from gapi.')
await signOut(firebaseAuth)
console.log('User is signed out from firebase.')
// clean user from store
} catch (error) {
console.error('signOutUser (firebase/auth.js): ', error)
}
}
export { signInPopup, signOutUser }
Run Code Online (Sandbox Code Playgroud)
但是,您应该小心使用这种方法,因为您必须立即从这两个服务中注销用户。
归档时间: |
|
查看次数: |
521 次 |
最近记录: |