Firebase Authentication Javascript: setCookie for pending Credential for redirect

百般思念 提交于 2019-12-12 18:04:48

问题


I am trying to get the multiples auth to link using singinwithredirect. I grab the error .credential and use JSON.stringify to pass it through a cookie.

From there, I convert it back to an object by using JSON.parse, but when I tried to pass the credential object into result.user.link(credential), it's giving me an error stating:

firebase.js:74 Uncaught Error: link failed: First argument "credential" must be a valid credential

Do I have to convert JSON object into a Firebase object in order to pass it in the credential? What the object originally looks like:

Ef {accessToken: "EAAQmrlAUQpEBAL4oiPWEJy.......", provider: "facebook.com"}

What the object looks like after converting back to JSON from cookie ('string'):

Object {accessToken: "EAAQmrlAUQpEBAL4oiPWEJy.......", provider: "facebook.com"}

回答1:


You should be careful to remove cached accessToken and secret after you are done with them.

The parsed JSON is possibly not a valid firebase object to link the pending credentials. You must pass it into the firebase auth provider object first before linking.

// Read cookie
var pendingCred = document.cookie;

// Parse
var pendingCredObj = JSON.parse(pendingCred);

// Delete cookie
document.cookie ="pendingCred=" + null + "; expires=0";

// Link with appropriate auth provider object
if (pendingCredObj.provider == "twitter.com"){
    var pendingCredObjProv = firebase.auth.TwitterAuthProvider.credential(pendingCredObj.accessToken, pendingCredObj.secret);
} else if (pendingCredObj.provider == "facebook.com"){
    var pendingCredObjProv = firebase.auth.FacebookAuthProvider.credential(pendingCredObj);
} else if (pendingCredObj.provider == "google.com"){
    var pendingCredObjProv = firebase.auth.GoogleAuthProvider.credential(pendingCredObj);
} else if (pendingCredObj.provider == "password"){
    var pendingCredObjProv = firebase.auth.EmailAuthProvider.credential(pendingCredObj);
}

// Link pending credentials to original user account
auth.currentUser.link(pendingCredObjProv).then(function(user) {
    console.log("Account linking success", user);
}, function(error) {
    console.log("Account linking error", error);
});



回答2:


First I recommend that you use sessionStorage instead of cookies as this contains an OAuth access token which you don't want to leak on page close.

After you parse the json object. Check the provider field. Based on that you can figure out what type of credential it is. For example if provider is facbeook.com:

var cred = firebase.auth.FacebookAuthProvider.credential(obj['accessToken');

In that case you would initialize the credential with the accessToken in the parsed object.



来源:https://stackoverflow.com/questions/39402293/firebase-authentication-javascript-setcookie-for-pending-credential-for-redirec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!