如何将Firebase身份验证令牌从客户端传递到服务器? [英] How to pass Firebase Auth Token from client to server?

查看:148
本文介绍了如何将Firebase身份验证令牌从客户端传递到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在工作的网站使用Firebase身份验证,并且登录的不同用户对他们可以访问哪些页面具有不同的权限.

The website that I'm working on uses Firebase authentication and different users that login have different permissions as to which pages they can visit.

设置登录方式类似于此帖子:

The way signing in is setup is similar to this post:

  1. 用户使用两个参数-"id"和"email"登录
  2. 服务器使用它们创建一个自定义的"uid",然后使用Firebase Admin SDK创建一个自定义令牌,并将其发送回客户端.
  3. 客户端使用Javascript Firebase SDK登录-firebase.auth().signInWithCustomToken()
  4. 现在用户已登录,他们可以单击不同的页面-即'/foo','/bar'

我遇到的问题是,当他们访问新页面时,我正在尝试将令牌从客户端传递回服务器(几乎与此

The issue I'm running into is that when they visit new pages, I'm trying to pass the token from the client back to the server (almost identical to how its done in this Firebase Doc ), verify the token & check if it has permission to view the webpage.

我正在尝试找出最佳的方法(也是最安全的方法).我考虑了以下选项:

I'm trying to figure out the best (& most secure) way to do this. I've considered the following option:

  • 使用令牌构造URL,但是我听说这不是一个好习惯,因为令牌被公开了,会话劫持变得容易得多.

我一直在尝试在请求标头中传递令牌,但据我了解,当用户单击指向其他页面的链接(或如果它在javascript中重定向)时,您无法添加标头.同样的问题也适用于使用POST.

I've been trying to pass the token in the request header, but from my understanding you can't add headers when the user clicks on a link to a different page (or if its redirected in javascript). The same issue applies to using POST.

当用户单击指向其他页面的链接时,该如何安全地将此信息传递给服务器并检查权限?

What can I do to securely pass this information to the server and check permissions when a user clicks on a link to a different page?

推荐答案

您可以通过以下方式在客户端获取accessToken(idToken):

You can get the accessToken (idToken) on client side by:

var accessToken = null;

firebase.auth().currentUser
    .getIdToken()
    .then(function (token) {
        accessToken = token;
    });

并将其传递到您的请求标头中:

and pass it in your request headers:

request.headers['Authorization'] = 'Bearer ' + accessToken;

,然后在服务器端使用首选方法获取令牌,并使用Firebase Admin SDK验证请求,例如(Node.js):

and on your server side get the token with your prefered method and authenticate the request with Firebase Admin SDK, like (Node.js):

firebaseAdmin.auth()
    .verifyIdToken(accessToken)
    .then(decodedIdToken => {
        return firebaseAdmin.auth().getUser(decodedIdToken.uid);
    })
    .then(user => {
        // Do whatever you want with the user.
    });

这篇关于如何将Firebase身份验证令牌从客户端传递到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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