简体   繁体   中英

Cloud Functions | Login into Firebase and return access token

I'm doing the backend in Laravel/PHP of an Android app. The PHP SDK isn't complete at the moment so I decided to use Cloud Functions to manage the Auth in Firebase.

I have my own auth system in my server, the only thing that I need is to make and endpoint (using Cloud Functions) to login into firebase with email/password and return an access_token .

I'm absuletly new in Node, but it seems to be easy. But I can't find a direct way to doing this, the majority of tutorials do it in the front-end of an Angular app.

Thanks in advance.

You'll want to learn how to use the Firebase Admin SDK to manage users . Then you can create a custom token . There is sample code for this.

You would need to include the client module, something like (winging it here):

exports.signIn = functions.https.onRequest((req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  firebase.auth().signInWithEmailAndPassword(email, password)
    .then(user = > {
      return user.getIdToken().then(idToken => {
        res.status(200).json({idToken: idToken});
      })
    })
    .catch(error => {
      res.status(400).json(error.toJSON());
    });
});

Keep in mind you may get throttled as you are sending many client requests from the same endpoint.

the only thing that I need is to make and endpoint (using Cloud Functions) to login into firebase with email/password and return an access_token.

Correct me if I'm wrong, but it seems that the Firebase Auth client SDK cannot be used in Cloud Functions.

My solution to this problem was to just directly use the Google Authentication API from inside the cloud function to get the access token for a given set of credentials.

Using the endpoint (documentation here ):

var signInEndpoint = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=" + firebase_client_auth_apiKey;

var email = "user@example.com"
var password = "password"

axios.post(signInEndpoint, {
        email: email,
        password: password,
        returnSecureToken: true
    }).then(async (res) => {
        console.log(res.data.idToken)    //logs the id token of the user
    });

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