【发布时间】:2021-07-09 09:01:50
【问题描述】:
我正在尝试使用 firebase 身份验证来获取 google 访问令牌,以便调用 youtube API。
我最初能够像这样获得访问令牌:
const provider = firebase.auth.GoogleAuthProvider();
cosnt scopes = []; // ...scopes
scopes.forEach(scope => provider.addScope(scope));
firebase.auth().signInWithPopUp(provider)
.then(userCredentials=> {
const oauthCredentials = userCredentials.credentials;
// using credentials for API calls
axios.get("some-google-api-path", { params: { access_token: oauthCredentials.accessToken } }); // and so on...
});
在访问令牌过期之前,这可以正常工作。 据我所知,firebase 似乎会自动刷新会话,但我可以找到一种方法来获取新的访问令牌。
我试过了:
firebase.auth().onAuthStateChange(user => {
// could not find the access token on the user object
});
由于失败了,我尝试手动使用:
const token = firebase.auth.GoogleAuthProvider.credential(
oauthCredentials.idToken,
oauthCredentials.accessToken
);
const authResult = await firebase.auth().signInWithCredential(token);
问题是authResult 将只包含idToken 或accessToken,但不能同时包含两者,这取决于我赋予firebase.auth.GoogleAuthProvider.credential 函数的内容。
我错过了什么吗? 还有其他/更好的方法吗?
【问题讨论】:
标签: javascript firebase firebase-authentication