Calling a Cloud Function from Android through Firebase

前端 未结 4 1152
花落未央
花落未央 2020-12-25 14:53

Situation

I have created a Google Cloud Function through functions.https.onRequest, which is working nicely when I paste its URL in a browser and integ

4条回答
  •  情深已故
    2020-12-25 15:20

    It isn't possible for now but as mentioned in the other answer, you can trigger functions using an HTTP request from Android. If you do so, it's important that you protect your functions with an authentication mechanism. Here's a basic example:

    'use strict';
    
    var functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);
    
    exports.helloWorld = functions.https.onRequest((request, response) => {
      console.log('helloWorld called');
      if (!request.headers.authorization) {
          console.error('No Firebase ID token was passed');
          response.status(403).send('Unauthorized');
          return;
      }
      admin.auth().verifyIdToken(request.headers.authorization).then(decodedIdToken => {
        console.log('ID Token correctly decoded', decodedIdToken);
        request.user = decodedIdToken;
        response.send(request.body.name +', Hello from Firebase!');
      }).catch(error => {
        console.error('Error while verifying Firebase ID token:', error);
        response.status(403).send('Unauthorized');
      });
    });
    

    To get the token in Android you should use this and then add it to your request like this:

    connection = (HttpsURLConnection) url.openConnection();
    ...
    connection.setRequestProperty("Authorization", token);
    

提交回复
热议问题