IndexedDB 如何从IndexDB中获取Firebase Auth令牌以进行 AJAX 调用

kknvjkwl  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(2)|浏览(224)

I'm working on a mobile site, hosted with Node.js / Express and which is "lightly" secured via Firebase Phone Authentication. When first loaded, the site is basically empty. After initial Firebase Phone authentication, the JWT token is sent to the node server via AJAX call. Server checks token, verifies the user is authorized, then sends back html content for the site.
So far, so good. This is a great way to protect display content on a simple single page web app.
But here is my current dilemma. I now want to submit data from a form on the site. The blank form was created with the first AJAX call.
After form submit, I'd like to resubmit the same JWT token to accompany an additional AJAX request for data submission to the server. It's not clear to me on how to obtain the token. I'm no longer inside the chained promise that got me the token in the first place... (i.e. I don't have access to the User Object anymore.) I can see the token stored in IndexedDB --> FirebaseLocalStorageDB --> FirebaseLocalStorage Object --> Key: Value (fbase_key.value.stsTokenManager.accessToken )
Here's a screen print of my dev tools in Chrome Browser.

I'm really not sure how to access that token from JavaScript in the browser client. Any ideas on how to get there from here?
Note: All of my initial client script code was contained within

$(document).ready(function () {
...
}

Because of timing and function .on() binding, the subsequent script content for my data form was served after the initial Ajax call post authentication.
Sample code for the initial AJAX submit... Obviously the form data submit to the server will contain a JSON object payload.

var authUserAjaxRequest = function (jwt) {
        console.log("authUserAjaxRequest started...");
        $.ajax({
            type: "POST", 
            url: '/fb', //the url to call
            data: {
                data: 'testData'
            }, //Data sent to server
            dataType: "json",
            beforeSend: function (xhr) { //Include the bearer token in header
                xhr.setRequestHeader("Authorization", 'Bearer ' + jwt)
            }
        }).then(function (response) {
            $('#admin_note_loc').html(response.admin_note);
            $('#page2_data').html(response.page2_data);
            $('#page3_summary').html(response.page3_summary);
            $('#page4_team').html(response.page4_team);
        }).fail(function (err) {  //Error during request
        console.log("AuthUserReq Error: ", err);
    });

Here's a reference. And another. This reference seems pretty outdated, or I'm just doing it wrong. Specific hints are appreciated.

bzzcjhmw

bzzcjhmw1#

这里有一个解决方案,但它可能不是最好的。
我有一个小范围的问题。对于我所有的原始javascript代码,我使用

$(document).ready(function () {
...
}

这段代码运行良好,允许我进行身份验证、获取令牌、重新提交等。
在那里我有一些代码

var handleSignedInUser = function (user) {
    // do stuff to display / block key elements on the site.

    user.getIdToken().then(function (token) {
        console.log("getIdToken(): ", token);  // <--  I added this line
        authUserAjaxRequest(token);
    })
};

不幸的是,由于 AJAX 的特性,我无法在$(document).ready() Package 中包含它们的控制JavaScript。在将$().on('click'..)函数绑定到新创建的表单元素时遇到了一些问题。
还记得我们使用Microsoft基础类(MFC)并添加句柄来链接关键特性的好日子吗?这给了我一个想法。
我在原始脚本中添加了一个全局变量var firebaseGlobalObject = {};,在$(document).ready(function () {...之前
初始化Firebase身份验证工具后,我复制了一个全局变量...

// Initialize Firebase
var config = {
    apiKey: "...",
    authDomain: "....firebaseapp.com",
    databaseURL: "https://....firebaseio.com",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "..."
};
firebase.initializeApp(config);
firebaseGlobalObject = firebase;   // <--- total hack

然后是在Chrome开发工具控制台中播放...
我想出了这个美丽的...
console.log(firebaseGlobalObject.auth().currentUser.qa)
完全黑客,但它肯定显示完全相同的令牌作为getIdToken()(在我的初始代码),并显示在IndexedDB --〉FirebaseLocalStorageDB --〉FirebaseLocalStorage对象--〉键:值(fbase_key.value. stsToken管理器.访问令牌)
显然,当我使用控制台时,我是在全局上下文中。所以我认为我可以使它工作。我会说,我不知道为什么有人选择.qa作为索引。在firebaseGlobalObject.auth().currentUser处有一堆可见的描述性属性;但不是令牌。
除了黑客攻击(可能会在X个月后的下一次firebase更新中失败),还有人有其他办法来解决这个困境吗?

r1zhe5dt

r1zhe5dt2#

firebase.auth().currentUser.getIdToken(true)
.then((tokenId)=>{
//Your code
})

https://firebase.google.com/docs/auth/admin/verify-id-tokens#web

相关问题