我想在我的应用中添加按钮'使用google登录”,我正在尝试使用node js中的firebase进行身份验证。我没有从firebase官方站点获得任何示例,该站点提供了Java脚本的文档。
请在下面找到代码段:
const firebaseAdmin = require('firebase-admin');
const serviceAccount = require('./SAK.json');
const FirebaseAuth = require('firebaseauth');
const authProvider = new FirebaseAuth("API_KEY");
const authToken = FirebaseAuth.initTokenMiddleware(serviceAccount);
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount)
});
router.get('/loginWithGoogle/', (req,res) => {
authProvider.loginWithGoogle(authToken, function(err, result) {
if (err) {
console.log('err');
}
else {
console.log(result);
}
});
});
我猜authToken值为null。我收到以下错误:
TypeError:无法读取null的属性'trim'在loginWithProviderID(/workspace/sodiumBackend/node_modules/firebaseauth/dist/providers/social-providers.js:22:23)在Object.loginWithGoogle(/workspace/sodiumBackend/node_modules/firebaseauth/dist/providers/social-providers.js:57:5)在FirebaseAuth.loginWithGoogle(/workspace/sodiumBackend/node_modules/firebaseauth/dist/index.js:61:25)在router.get(/workspace/sodiumBackend/src/routes/api/user.js:8:18)在Layer.handle [作为handle_request](/workspace/sodiumBackend/node_modules/express/lib/router/layer.js:95:5)在下一个(/workspace/sodiumBackend/node_modules/express/lib/router/route.js:137:13)在Route.dispatch(/workspace/sodiumBackend/node_modules/express/lib/router/route.js:112:3)在Layer.handle [作为handle_request](/workspace/sodiumBackend/node_modules/express/lib/router/layer.js:95:5)
嗨,首先,请检查firebase Admin中“管理用户”的文档。
https://firebase.google.com/docs/auth/admin/manage-users
注意firebase createUser方法
admin.auth().createUser({
email: '[email protected]',
emailVerified: false,
phoneNumber: '+11234567890',
password: 'secretPassword',
displayName: 'John Doe',
photoURL: 'http://www.example.com/12345678/photo.png',
disabled: false
})
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log('Successfully created new user:', userRecord.uid);
})
.catch(function(error) {
console.log('Error creating new user:', error);
});
“默认情况下,Firebase身份验证将为新用户生成一个随机uid。”
创建用户后,您可以为其创建令牌
var myTokenToSave;
admin
.auth()
.createCustomToken(userRecord.uid)
.then(function(customToken) {
myTokenToSave = customToken;
});
然后最终对其进行身份验证
admin.auth().verifyIdToken(idToken)
.then(function(decodedToken) {
let uid = decodedToken.uid;
// ...
}).catch(function(error) {
// Handle error
});
希望这有意义,代码的放置和使用取决于您的实现。