How to pass Firebase Auth Token from client to server?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-20 10:33:15

问题


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. User Logins in with two parameters - "id" and "email"
  2. Server uses these to create a custom "uid", then uses the Firebase Admin SDK to create a custom token that is sent back to the client.
  3. The client logs in with the Javascript Firebase SDK - firebase.auth().signInWithCustomToken()
  4. Now that the user is logged in, they can click different pages - i.e. '/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:

  • Construct a URL with the token, but I've heard this isn't good practice because the token is getting exposed and session hijacking becomes a lot easier.

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?


回答1:


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;

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.
    });


来源:https://stackoverflow.com/questions/43195612/how-to-pass-firebase-auth-token-from-client-to-server

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