flutteroauth-2.0firebase-authenticationfirebase-cloud-messaging

How to authorize a request to the FCM v1 API with an access token


I have ID Device token that I get from firebase_messaging package by running this code:

FirebaseMessaging messaging = FirebaseMessaging.instance;
String? token = await messaging.getToken();
print("DEVICE TOKEN $token");

I have ID Token and Access Token from package firebase_auth by runnig this code:

final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();

final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

final UserCredential userCredential = await _auth.signInWithCredential(credential);
final User? user = userCredential.user;

final idToken = await user.getIdToken();
final accessToken = googleAuth.accessToken;

print('ID Token: $idToken');
print('Access Token: $accessToken');

Now, I have value DEVICE TOKEN, ID Token, Access Token and I try to send one to one notification using api postman, here is the postman property:

POST : https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

{
   "message":{
      "token":"DEVICE TOKEN",
      "notification":{
        "body":"This is an FCM notification message!",
        "title":"FCM Message"
      }
   }
}

for the header:

Authorization: Bearer "MY Access Token"

and I got the result:

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

Is there a way to solve this, honestly I little bit confuse because I have value DEVICE TOKEN, ID Token, Access Token, but I don't use ID Token when sending payload in postman


Solution

  • According to the documentation on authorizing send requests to the FCM v1 API the access token should be generated from a service account, which is not what your code seems to be doing.

    Base your implementation on the code sample in that documentation here. You'll note that there's no code sample of doing this in Flutter, because (as I also commented on your previous question) this process should run in a trusted environment - not in your Flutter app.