使用 Firebase 函数验证 ID 令牌时出现内部服务器错误

问题描述 投票:0回答:1

我正在尝试添加一个 Firebase 函数来验证 http 请求给出的 id 令牌,以验证用户,然后再让他访问我的远程数据库。 我尝试使用 Node.js

中的文档进行一些操作

这是我的代码:

const { initializeApp } = require('firebase-admin/app');
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountCred.json");

const app = initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

exports.verifyToken = onRequest((req, res) => {
    const { uid, token } = req.query;

    if (!uid || !token) {
        res.status(400).send('Paramètres manquants : uid et token sont requis.');
        return;
    }

    app.Auth().verifyIdToken(token).then((decodedToken) => {
        if (decodedToken.uid === uid) {
            res.status(200).send('Token valide.');
        } else {
            res.status(401).send('Token invalide.');
        }
    }).catch((error) => {
        res.status(500).send(error.message);
    });
});

但是,使用此代码,我不断收到此错误:

Internal Server Error : 500

这是我的Flutter请求代码:

Future<void> validateTokenDB() async {
    String token="";

    try {
      token = await getIdToken() ?? "";
    } catch (e) {
      // Handle error
      print('Error getting token: $e');
    }

    String uid = firebaseAuth.currentUser!.uid;

    // Creating the query parameters
    Map<String, String> queryParams = {
      'uid': uid,
      'token': token,
    };

    // Constructing the URL with query parameters
    Uri url = Uri(
      scheme: 'https',
      host: 'link-to-the-function-url.a.run.app',
      queryParameters: queryParams,
    );

    try {
      // Sending the HTTP request
      http.Response response = await http.get(url);

      // Handling the response
      if (response.statusCode == 200) {
        // Request was successful
        print(response.body);
        print('Token updated successfully');
        return;
      } else {
        // Request failed
        print('${response.body} : ${response.statusCode}');
        Auth().signOut();
      }
    } catch (e) {
      // Error occurred during HTTP request
      print('Error during HTTP request: $e');
      Auth().signOut();
    }
    Auth().signOut();
  }

希望你能帮我解决这个错误。

node.js flutter firebase firebase-authentication google-cloud-functions
1个回答
0
投票

这是我的代码,它对我有用,希望它能为您提供帮助,只需根据您的需要更改您想要的内容,例如信用路径:

// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const {onRequest} = require("firebase-functions/v2/https");
var admin = require("firebase-admin");
var serviceAccount = require("path/to/firebase-credentials.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

exports.verifyToken = onRequest( async (req, res) => {
    const { uid, token } = req.query;

    if (!uid || !token) {
        res.status(400).send('Paramètres manquants : uid et token sont requis.');
        return;
    }

    try {
        const authUser = await admin.auth().verifyIdToken(token);
        if (authUser.uid !== uid) {
            res.status(403).send('Token invalide :' + authUser.uid + ' !== ' + uid);
            return;
        } else {
            res.status(200).send('Token valide.');
        }
    } catch (error) {
        res.status(error.status).send(error.message);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.