使用 python firebase-admin 验证 firebase google 登录提供商令牌时面临问题

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

我有一个 flutter 客户端应用程序,用于使用两个提供程序登录用户:

  1. 电子邮件密码提供商
  2. Google 登录提供商

为这两个函数添加代码片段:

Future<String?> signInWithEmailPassword(String email, String password) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
      if (!_auth.currentUser!.emailVerified) {
        return "Please verify your email before signing in.";
      }
      notifyListeners();
      return "success";
    } on FirebaseAuthException catch (e) {
      return handleAuthException(e);
    }
  }
Future<String?> signInWithGoogle() async {
    try {
      final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
      if (googleUser != null) {
        final GoogleSignInAuthentication googleAuth =
            await googleUser.authentication;
        final AuthCredential credential = GoogleAuthProvider.credential(
          accessToken: googleAuth.accessToken,
          idToken: googleAuth.idToken,
        );
        UserCredential userCredential =
            await _auth.signInWithCredential(credential);
        await userCredential.user!.sendEmailVerification();
        notifyListeners();
        return "success";
      }
      return "Google sign-in canceled";
    } on FirebaseAuthException catch (e) {
      return handleAuthException(e);
    } catch (e) {
      return e.toString();
    }
  }

在屏幕上,为了获取令牌,我使用以下函数来打印 current_user 的令牌:

Future<void> printCurrentUserToken() async {
    if (currentUser != null) {
      String? token = await currentUser!.getIdToken();
      if (kDebugMode) {
        print("Firebase Auth Token: $token");
      }
    } else {
      if (kDebugMode) {
        print("No user is currently logged in.");
      }
    }
  }

现在我面临的问题是使用密码登录提供程序获取的令牌工作正常,在我的 Fastapi-python 后端初始化的 firebase-admin 应用程序能够验证这一点,但是对于 google-sign- 之后获取的令牌在,我得到:

Failed to verify token: Could not verify token signature.

作为参考,我使用以下脚本来测试令牌:

import firebase_admin
from firebase_admin import credentials, auth
from dotenv import load_dotenv
import pathlib


# we need to load the env file because it contains the GOOGLE_APPLICATION_CREDENTIALS
basedir = pathlib.Path(__file__).parents[1]
print(basedir)

load_dotenv(basedir / ".env")

firebase_admin.initialize_app()

print("Current App Name:", firebase_admin.get_app().project_id) <- Getting proper firebase project ID


# Replace 'your_token_here' with the actual token
token = "<Fetched-Token>"
try:
    decoded_token = auth.verify_id_token(token)
    print("Token is valid.")
    print(decoded_token)
except Exception as e:
    print(f"Failed to verify token: {e}")

为了确保令牌的结构正确,我还尝试使用 jwt 和以下脚本来解码令牌:

import jwt

def decode_token_without_verification(token):
    decoded_token = jwt.decode(token, options={"verify_signature": False})
    return decoded_token

# Example usage
google_signin_token = "<google-sign-in-token>"
password_token = "<password-token>"


print("Google Sign-In Token:", decode_token_without_verification(google_signin_token))
print("Password Provider Token:", decode_token_without_verification(password_token))

我得到的回复:

venv)python3 ./tests/token_decode.py 

Google Sign-In Token: {'name': '<correct_name>', 'picture': 'https://lh3.googleusercontent.com/a/ACg8ocLcB9dzAt1mNlczH_dcU94py7MU_02WOeZOb8Z0C5TYsGYpgQ=s96-c', 'iss': 'https://securetoken.google.com/<correct-project>', 'aud': '<correct-project>', 'auth_time': 1716404913, 'user_id': '<correct_user_id>', 'sub': '<sub_id>', 'iat': 1716404913, 'exp': 1716408513, 'email': '<correct_email>', 'email_verified': True, 'firebase': {'identities': {'google.com': ['ID'], 'email': ['<correct_email>']}, 'sign_in_provider': 'google.com'}}


Password Provider Token: {'iss': 'https://securetoken.google.com/<correct-project>', 'aud': '<correct-project>', 'auth_time': 1716403137, 'user_id': '<correct-uid>', 'sub': '<sub_id>', 'iat': 1716403137, 'exp': 1716406737, 'email': '<Correct_email>', 'email_verified': True, 'phone_number': '<phone_number>', 'firebase': {'identities': {'email': ['<Correct_email>'], 'phone': ['<phone_number>']}, 'sign_in_provider': 'password'}}
firebase firebase-authentication google-oauth firebase-admin
1个回答
0
投票

所以..这将是相当反气候的。 问题是,flutter-dart 的打印截断了令牌。使其无效,使用“dart:developer”中的developer.log 并获得了完整的令牌(当然)正在工作!

© www.soinside.com 2019 - 2024. All rights reserved.