本文介绍了如何从firebase_auth获取令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Firebase获取身份验证令牌(电子邮件和密码身份验证)以在我的Firebase云功能中进行身份验证.似乎函数getIdToken()和getToken()都不适用于firebase_auth软件包.

I'd like to get the auth token from firebase (email and password auth) to authenticate in my firebase cloud function. It seems like the functions getIdToken() and getToken() are both not working for firebase_auth package.

还有其他功能或者有更好的主意,以确保只有经过身份验证的用户才能触发云功能?

is there an other function or is there even a better idea to make sure only authenticated users can trigger the cloud functions?

var token = await FirebaseAuth.instance.currentUser.getIdToken();
var response = await httpClient.get(url,headers: {'Authorization':"Bearer $token"});

推荐答案

我在这一点上同意@Doug-callable可以为您包装它,并且会更容易-但我的用例要求我进行HTTPS调用(在功能中).另外,我认为您只是走在正确的道路上-但您可能未在自己的Cloud Functions中对其进行检查.

I agree with @Doug on this one - callable wraps this for you and will be easier -, but my use case required me to make HTTPS calls (onRequest in Functions). Also, I think you're just in the correct path - but you're possibly not checking it in your Cloud Functions.

在您的应用中,您将致电:

In your app, you'll call:

_httpsCall() async {
  // Fetch the currentUser, and then get its id token
  final user = await FirebaseAuth.instance.currentUser();
  final idToken = await user.getIdToken();
  final token = idToken.token;

  // Create authorization header
  final header = { "authorization": 'Bearer $token' };

  get("http://YOUR_PROJECT_BASE_URL/httpsFunction", headers: header)
  .then((response) {
    final status = response.statusCode;
    print('STATUS CODE: $status');
  })
  .catchError((e) {
    print(e);
  });
}

在您的函数中,您将检查令牌:

In your function, you'll check for the token:

export const httpsFunction = functions.https.onRequest((request, response) => {
  const authorization = request.header("authorization")

  if (authorization) {
    const idToken = authorization.split('Bearer ')[1]
    if (!idToken) {
      response.status(400).send({ response: "Unauthenticated request!" })
      return
    }

    return admin.auth().verifyIdToken(idToken)
    .then(decodedToken => {
      // You can check for your custom claims here as well
      response.status(200).send({ response: "Authenticated request!" })
    })
    .catch(err => {
      response.status(400).send({ response: "Unauthenticated request!" })
    })
  }

  response.status(400).send({ response: "Unauthenticated request!" })
})

请紧记:

如果我没记错的话,这些令牌有效期为1个小时,如果您要将它们存储在某个地方,请注意这一点.我已经在本地进行了测试,每次仅花费200〜500毫秒-仅获得id令牌,这在大多数情况下并没有那么大的开销-但意义重大.

If I'm not mistaken, those tokens are valid for 1 hour, if you are going to store them somewhere, just be aware of this. I've tested locally and it takes around 200~500ms - every time - to get only the id token, which in most cases are not that big of overhead - but is significant.

这篇关于如何从firebase_auth获取令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 11:36