需求是在 Vue 项目上同时接入 Google 登陆和 Facebook 登陆。查阅文档发现 firebase 提供了,Google 和 Facebook 等多家联合验证方式。也就是最终拿到各个平台等 token 之后都要再通过 firebase 做最后的验证,生成 firebase 验证后的 token,可以节省后端的开发时间。但前端仍然要去集成各自的 sdk ,文章以 Google 和 Facebook 为例,先介绍项目相关配置。
账号配置 1.firebase先创建应用,然后在 Authentication 下的 Sign-in method 添加要登陆的第三方平台,并配置相关参数。同时也要添加已获授权的网域,本地调试的话如果不加localhost是无法通过验证的。
使用 Google 登陆并开启网页登陆,需要配置额外的"网页客户端 ID",和“网页客户端密钥”,根据提示去创建凭据,并将创建好的凭据,设置保存。
和 firebase 相似,注册好自己的应用,会得到一个 应用ID和密钥,
这里需要注意一点,如果在本地调试的话这里的域名需要改成自己本地的,否则会验证不通过,包括下面填写的网站地址,图没截进来,翻到底部能看到。
这里只是注册完了 Facebook, 但如果想要通过 firebase 验证还需要关联账号,
回到 firebase 管理后台,图一的地方有个 Facebook 开启的选项,把 Facebook 的应用 ID 和 密钥填上
最后还得回到 Facebook 后台配置重定向,把上面的 URL 复制拷贝过来。到这里才算完成整个配置
这里只用安装 firebase 的sdk
npm install firebase 2.初始化sdk首先打开 firebase 控制台,找到设置从里面下拉找到这段配置信息复制出来,不要改动里面的信息。
初始化 firebase
import firebase from "firebase";firebase.initializeApp({ apiKey: "xxxxx", authDomain: "goodjob-xxxxx.firebaseapp.com", databaseURL: "https://goodjob-xxxxx.firebaseio.com", projectId: "goodjob-xxxxx", storageBucket: "goodjob-xxxxx.appspot.com", messagingSenderId: "xxxxx", appId: "1:xxxxx:web:xxxxx", measurementId: "G-xxxxx", });初始化 Facebook
将xxxx替换为自己的appID
初始化建议放在 created() 方法内,
3.获取对应的验证 token需分别获取 Google 和 Facebook token,当然如果集成了其它第三方登陆的话,也是需要先获取对应的 token
Google登陆:
var provider = new firebase.auth.GoogleAuthProvider(); firebase .auth() .signInWithPopup(provider) .then(function (result) { // This gives you a Google Access Token. You can use it to access the Google API. var accessToken = result.credential.accessToken; var idToken = result.credential.idToken; // The signed-in user info. var user = result.user; console.log(accessToken); }) .catch(function (error) { console.log("credential:" + error.message); });Facebook登陆:
FB.getLoginStatus(function (response) { // Called after the JS SDK has been initialized. console.log(response); if (response.status === "connected") { var accessToken = response.authResponse.accessToken; console.log(accessToken); // 已登录 } else { // 未登录进行登录 FB.login(function (res) { console.log("login:" + res); if (res.status === "connected") { } else { // The person is not logged into your webpage or we are unable to tell. } }); } }); 4.firebase 验证并生成新的 firebase token使用 firebase 的 Credential 验证,各个平台的 Credential 都不同,需要调用对应的方法拿到 Credential 结果传递给 firebase。
//Googlevar credential = firebase.auth.GoogleAuthProvider.credential( idToken, accessToken );//Facebookvar credential = firebase.auth.FacebookAuthProvider.credential( accessToken );验证:
var auth = await firebase.auth().signInWithCredential(credential)如果验证成功则在 firebase 的控制台能看到对应的用户信息
最后一步
需要获取idToken,用来给后端提供验证token
到这里就成功了,接下来如何将用户保存到自己到服务器那就需要后端开发人员开发相应的接口了。
总结虽然看似简单,但是集成的过程中还是遇到不少坑,每一步都不可少。而且还需要科学上网才可以。
排错方法:首先要保证自己访问 Google 网站没问题,其次看是否能拉取授权窗口,如果能拉取登陆,但是登陆后出问题,检查后台配置 重定向及域名相关设置是否正确,如果能正确拿到对应平台的token,但是最后 firebase auth 验证出错,检查开启的登陆方式中,对应的第三方参数配置是否有误。