如何从python后端正确验证firebase身份验证令牌?

时间:2021-06-06 10:13:53

标签: python reactjs firebase google-cloud-platform firebase-authentication

最终目标:创建以下管道:

User login to client app --> jwt tokens --> python server 
 --> verify tokens --> retrieve user_id 
--> use user_id to access multiple backend services based on token state.

说明

我有一个小型前端服务,可让用户使用 google 登录。用户可以正确注册,我正在 firebase auth 数据库中获取他们的详细信息。成功登录后,我们通过以下方法从 firebase 获取一个 auth 令牌。

firebase.auth()
  .signInWithPopup(provider)
  .then((result) => {
    var credential = result.credential;
    var token = credential.accessToken;
    var user = result.user;
  }).catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    var email = error.email;
    var credential = error.credential;
  });
我从 firebase documentation 中取的。

然后我们将这个检索到的令牌发送到python后端,它使用:

cred = credentials.Certificate('/path/to/service/account/key.json')
app = firebase_admin.initialize_app(cred)

token = 'eyJhbGci1iJSUzI1NiIsImtpZCI6ImFiMGNiMTk5Zjg3MGYyOGUyOTg5YWI0ODFjYzJlNDdlMGUyY2MxOWQiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiSGFyc2hpdCBDaG9wcmEiLCJwaWN0dXJlIjoiaHR0cHM6Ly9saDMuZ29vZ2xldXNlcmNvbnRlbnQuY29tL2EvQUFUWEFKd21nT01LUnBucnFvMDVqVmRkRTF5TVRpcmxiNGxRMWkxZG9SQmlXeDg9czk2LWMiLCJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vYmV0YS1zY2hvbGFybHlzIiwiYXVkIjoiYmV0YS1zY2hvbGFybHlzIiwiYXV0aF90aW1lIjoxNjIyOTE5OTA0LCJ1c2VyX2lkIjoiOTlrY2N2VmpPVFRWejBOTE5jUlBuTHRrZGg1MiIsInN1YiI6Ijk5a2NjdlZqT1RUVnowTkxOY1JQb'

decoded_token = auth.verify_id_token(token, app=app)
uid = decoded_token['uid']
print(uid)

当我运行上面的 python 代码段时,我收到以下错误:

firebase_admin._auth_utils.InvalidIdTokenError: Wrong number of segments in token: b'token'

我还观察到,我得到的令牌仅由一个句点 . 分隔。我被困在这里,非常感谢任何帮助。

0 个答案:

没有答案