简体   繁体   English

如何从 firebase_auth 获取令牌

[英]How to get the token from 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.我想从 firebase(电子邮件和密码身份验证)获取身份验证令牌以在我的 firebase 云 function 中进行身份验证。函数 getIdToken() 和 getToken() 似乎都不适用于 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?还有其他 function 还是有更好的主意来确保只有经过身份验证的用户才能触发云功能?

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

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).我同意@Doug 对此的看法 - callable 为您包装了它并且会更容易 - 但我的用例要求我进行 HTTPS 调用(函数中的onRequest )。 Also, I think you're just in the correct path - but you're possibly not checking it in your Cloud Functions.另外,我认为您只是在正确的路径上 - 但您可能没有在 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!" })
})

Keep in mind:记住:

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.如果我没记错的话,这些令牌的有效期为 1 小时,如果您要将它们存储在某个地方,请注意这一点。 I've tested locally and i t 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.我已经在本地进行了测试,每次都需要大约 200~500 毫秒才能获得 id 令牌,这在大多数情况下并不是那么大的开销 - 但很重要。

It's going to be easiest for you to use a callable function , since that lets you:使用可调用函数对您来说将是最简单的,因为它可以让您:

  1. Automatically send the current user's uid in the request.请求中自动发送当前用户的uid。
  2. Know very easily on the function side if a UID was provided in the request, and refuse service if none was provided.如果在请求中提供了 UID,在功能方面很容易知道,如果没有提供,则拒绝服务。

The flutter plugin is here .颤振插件在这里

You should be able to do the equivalent work yourself, though, since callable functions are just a wrapper around normal HTTP connections.不过,您应该能够自己完成等效的工作,因为可调用函数只是普通 HTTP 连接的包装器。 It's possible for you to get the ID token of the logged in user.您可以获取登录用户的 ID 令牌。

import 'package:firebase_messaging/firebase_messaging.dart';
.
.
.

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

@override
Future<void> initState() {
  super.initState();

  _firebaseMessaging.getToken().then((token) {
    assert(token != null);
    print("teken is: " + token);
  });
}

Get your token from firebaseAuth and put in a string.从 firebaseAuth 获取您的令牌并放入一个字符串中。

Future<Details> getDetails() async {
  String bearer = await FirebaseAuth.instance.currentUser!.getIdToken();
  print("Bearer: " + bearer.toString());
  String token = "Bearer ${bearer}";
  var apiUrl = Uri.parse('Your url here');

  final response = await http.get(apiUrl, headers: {
    'Authorization' : '${token}'
  });

  final responseJson = jsonDecode(response.body);

  return Details.fromJson(responseJson);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter firebase_auth 中的无效应用凭证/令牌不匹配 - invalid-app-credential/Token mismatch in Flutter firebase_auth 如何解决“配置项目‘:firebase_auth’时出现问题。” - How to solve " A problem occurred configuring project ':firebase_auth'. " 为 firebase_auth 隐藏 EmailAuthProvider 的目的是什么? - What is the purpose of hiding EmailAuthProvider for firebase_auth? Dart Flutter 顺序 firebase_auth 错误 - Dart Flutter sequential firebase_auth errors OTP [firebase_auth/未知] null - OTP [firebase_auth/unknown] null GeneratedPluginConstraint,致命错误:找不到模块“firebase_auth”@import firebase_auth; - GeneratedPluginConstraint , Fatal error: module 'firebase_auth' not found @import firebase_auth; 如何使用 firebase_auth 包修复 flutter 应用程序中的 FirebaseAuth.instance.currentUser()? 它总是返回 null - How to fix FirebaseAuth.instance.currentUser() in flutter app using firebase_auth package? It is always returning null 如何获取 firebase 最后一个授权令牌刷新时间 - How to get firebase last auth token Refresh time 如何在 firebase_auth 中更新 FirebaseUser 的电话号码? - How do I update a FirebaseUser's phone number in firebase_auth? 如何在 flutter web 应用程序中正确添加和启用 firebase_auth? - How does one properly add and enable firebase_auth in a flutter web app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM