【问题标题】:How to authenticate user on server with firebase when they are already authenticated on client?当他们已经在客户端进行身份验证时,如何使用 firebase 在服务器上对用户进行身份验证?
【发布时间】:2017-12-12 14:51:11
【问题描述】:

我有一个 Angular 应用程序,它使用 firebase 对客户端上的用户进行身份验证。这似乎工作正常。

export class AuthService {
  user$: Observable<firebase.User>;

  constructor(private af_auth: AngularFireAuth) {
    this.user$ = this.af_auth.authState;
    this.user$.subscribe(user => {
      // do something with the firebase user
    });
  }

}

我还有一些基于服务器的东西在 node.js 中使用 express 运行。我想尝试验证点击我的端点的用户是否已经通过 firebase 对我的应用程序进行了身份验证。我可以这样做吗?

我想在 express 中有一个类似这样的路由处理程序:

var firebase_app = firebase.initializeApp(firebase_config); 

auth.isAuthenticated = function (req, res, next) {

    // I had seen a suggestion to do the following, but currentUser is always null here.
    var user = firebase_app.auth().currentUser;

    if (user !== null) {
        // Authenticated with my app?
        req.auth_user = user;
        next();
    } else {
        res.status(401).send({error: 'Nope'});
    }
};

如何从快速路由处理程序中得知我的用户已登录到我的应用程序?

【问题讨论】:

    标签: firebase firebase-authentication


    【解决方案1】:

    步骤 1 角度。将标头中的 Firebase 身份验证 ID 令牌从 Angular 发送到您的快速端点。

     postRequest() {
        const url = 'https://your-endpoint';
        firebase.auth().currentUser.getIdToken()
                .then(authToken => {
                  const headers = new Headers({'Authorization': 'Bearer ' + authToken });
                  return this.http.post(url, { someData } , { headers }).toPromise()
                })
        }
    

    步骤 2 节点。使用 Firebase 管理 SDK 解密身份验证令牌。 verifyIdToken 验证 Firebase ID 令牌 (JWT)。如果令牌有效,则通过令牌的解码声明来履行承诺;否则,promise 将被拒绝。

    const admin = require('firebase-admin');
    admin.initializeApp(yourConfig);
    const express = require('express')
    const app = express()
    
    app.post('/your-endpoint', (req, res) => {
    
      const token = req.headers.authorization.split('Bearer ')[1]
    
      return admin.auth().verifyIdToken(token)
                  .then(decodedToken => {
                      const uid = decodedToken.uid;
                      res.status(200).send('Looks good!')
    
                  })
                  .catch(err => res.status(403).send('Unauthorized'))
    
    
    });
    

    来源:

    https://jwt.io/

    https://firebase.google.com/docs/auth/admin/verify-id-tokens https://angularfirebase.com/lessons/secure-firebase-cloud-functions/

    【讨论】:

    • 这是完美的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多