简体   繁体   中英

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.

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"});

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!" })
})

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. 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.

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.
  2. Know very easily on the function side if a UID was provided in the request, and refuse service if none was provided.

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. It's possible for you to get the ID token of the logged in user.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM