存储和使用Firebase Auth令牌进行对我的服务器的API调用 [英] Storing and using the Firebase Auth Token for API calls to my server

查看:48
本文介绍了存储和使用Firebase Auth令牌进行对我的服务器的API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ReactNative项目中实现了Firebase 用于登录的电话验证.现在,我想使用此 JWTToken 传递给我对服务器进行的API调用

I implemented Firebase Phone Auth for SignIn in my ReactNative project. Now I want to use this JWTToken to be passed to the API calls that I make to my server.

在服务器端,我将验证通过API调用传递的令牌,并以适当的响应进行响应.我的问题是,如何在我对服务器进行的API调用中传递此令牌?

And at the server side, I would be validating the token which was passed through the API calls and respond with the proper response. My question is, how can I pass this token in the API calls that I make to my server?

  1. 我可以将令牌(在应用程序的第一个加载屏幕中,用于验证用户身份的令牌)存储在localStorage中,稍后再在任何屏幕中获取令牌以进行API调用
  2. 我可以在每个屏幕(计划从中进行API调用)中导入firebase程序包来直接访问令牌,如下所示:
  1. I can store the token (within my first loading screen of the app, where it authenticates the User) in the localStorage and fetch it later in any of my screens to make the API calls
  2. I can access the Token directly my importing the firebase package in each and every screen (from which am planning to do the API calls) like this: https://rnfirebase.io/reference/auth/idtokenresult and pass it in the API calls

但是我正在考虑将Token(在加载屏幕期间获取)存储在我的ReactNative项目内部的全局变量中,并且可以从任何屏幕进行访问.但是我找不到如何做到的?还是哪种方法更合适?

But I was thinking about storing the Token (fetched during the loading screen) in a global variable inside my ReactNative project and that can be accessed from any screens. But I couldn't find how this can be done? Or which one would be the more appropriate way to do this?

这是获取令牌的方式:

  auth().onIdTokenChanged(function(user) {
    if (user) {
      
      user.getIdToken().then( token => {
        console.log( token )
      });

    }
  });

推荐答案

从长远来看,将令牌存储在本地存储中效果不佳.ID令牌会在1小时后过期,并且此后将无法在服务器上成功验证.

Storing the token in local storage is not going to work out well for you in the long run. ID tokens expire after 1 hour, and will not successfully verify on the server after that.

每个页面都应设置一个ID令牌侦听器,以便它可以使用Firebase Auth SDK提供的最新令牌.SDK会自动刷新它,并在回调中为您提供最新的令牌.每次令牌更改时,都应在API调用中使用该值.使用 onIdTokenChanged():

Each individual page should set up an ID token listener so it can use the most fresh token provided by the Firebase Auth SDK. The SDK will automatically refresh it and provide you with the latest token in the callback. Every time the token changes, you should use that value in your API calls. Use onIdTokenChanged():

firebase.auth().onIdTokenChanged(function(user) {
  if (user) {
    // User is signed in or token was refreshed.
  }
});

这篇关于存储和使用Firebase Auth令牌进行对我的服务器的API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆