【问题标题】:Firebase how to authenticate user through native facebook appFirebase 如何通过本机 facebook 应用程序对用户进行身份验证
【发布时间】:2014-12-09 18:18:38
【问题描述】:
firebase 身份验证 api 使用浏览器弹出窗口(新 api 中的 Firebase.authWithOAuthPopup() cordova example )。然而,在手机上,大多数人使用原生的 Facebook 应用程序。对于 cordova 手机应用,通过 fb 原生应用进行身份验证的优点是不需要用户重新输入 facebook 用户名和密码。
如何使用 firebase api 实现 fb 原生应用身份验证?
如果 firebase 本身不支持 fb 原生应用身份验证,是否可以将 firebase 与似乎支持原生 fb 应用身份验证的 cordova facebook plugin 结合使用。这怎么可能?
【问题讨论】:
标签:
cordova
firebase
firebase-security
【解决方案1】:
authWithOAuthPopup() 方法不支持本机身份验证流程,但是,使用 Firebase 引用的 authWithOAuthToken() 方法,您可以使用 Cordova Facebook 插件返回的 OAuth 令牌登录 Firebase。
这是一个例子:
var dataRef = new Firebase('https://<your-firebase>.firebaseio.com');
facebookConnectPlugin.login(['public_info'], function(status) {
facebookConnectPlugin.getAccessToken(function(token) {
// Authenticate with Facebook using an existing OAuth 2.0 access token
dataRef.authWithOAuthToken("facebook", token, function(error, authData) {
if (error) {
console.log('Firebase login failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
}
});
}, function(error) {
console.log('Could not get access token', error);
});
}, function(error) {
console.log('An error occurred logging the user in', error);
});
【解决方案2】:
请注意,Firebase 3 略有变化。使用:
var user = {};
var config = {
apiKey: "<Your API Key",
authDomain: "<yourapp>.firebaseapp.com",
databaseURL: "https://<yourapp>.firebaseio.com",
storageBucket: "<yourapp>.appspot.com"
};
firebase.initializeApp(config);
// Sign in with Token obtained from facebookConnectPlugin.getAccessToken
var credential = firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth().signInWithCredential(credential).then(function(result) {
// The firebase.User instance:
user = result;
console.log('User :'+JSON.stringify(user));
//Can now user the 'user' here
}, function(error) {
// Check error.code and error.message
// Possible error is auth/account-exists-with-different-credential to fetch the providers ???
// In case of auth/account-exists-with-different-credential error,
// you can fetch the providers using this:
if (error.code === 'auth/account-exists-with-different-credential') {
firebase.auth().fetchProvidersForEmail(error.email).then(function(providers) {
// The returned 'providers' is a list of the available providers
// linked to the email address. Please refer to the guide for a more
// complete explanation on how to recover from this error.
});
}
});