Michalk
Michalk

Reputation: 23

Firebase JWT Authentication

In my application I don't have user login, but I want to secure my Firebase data. I use for this Firebase Token Generator - PHP. Access to the database is like Russian roulette. Once I have permissions, once not when I'm refreshing page.

here is my token generator file:

<?php
    require_once 'vendor/autoload.php';

    use Firebase\Token\TokenException;
    use Firebase\Token\TokenGenerator;

    try {
        $generator = new TokenGenerator('Firebase-Secret');
        $token = $generator
            ->setData(array('uid' => '123'))
            ->setOption('admin', true)
            ->create();
    } catch (TokenException $e) {
        echo "Error: ".$e->getMessage();
    }

    echo $token;

?>

here is index.php:

<script>var token = "<?= include_once 'getToken.php' ?>";</script>

$(document).ready(function(){

        firebaseRef.authWithCustomToken(token, function(error, authData) {
            console.log(authData)
        }, {remember: "sessionOnly" });


            // do something
})

Upvotes: 2

Views: 887

Answers (1)

Kato
Kato

Reputation: 40582

In the future, please include a minimal, complete repro for your debugging issues. Most likely, you are running into asynchronous issues. Your //do something code probably needs to move into the callback for auth.

$(document).ready(function(){
  firebaseRef.authWithCustomToken(token, function(error, authData) {
      console.log(authData);

      if( !error ) {
         // run your authenticated code here
      }

  }, {remember: "sessionOnly" });

  // trying to run something here that requires auth will
  // be non-deterministic

});

Upvotes: 1

Related Questions