Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularfire, firebase JSON Web Tokens - how to access to authentication data from token?

I have service in php that return token with custom data (authentication data):

  include_once "FirebaseToken.php";
  $secret = "***********";
  $tokenGen = new Services_FirebaseTokenGenerator($secret);
  $token = $tokenGen->createToken(array("name" => "ADMIN"),array( admin => true));
  echo $token;

Then in angular i have function for login:

adminlogin: function(){
  var token;
  $http.get("http://****").success(function(data){token=data;})
    .then(function(){
       var dataRef = new Firebase(FBURL);
         dataRef.auth(token, function(error) {
          if(error) {
            console.log("Login Failed!", error);
          } else {
            console.log("DISPLAY name FROM TOKEN");
          }
        });
      })

And after authentication i want to show name from token. How to access to authentication data from token ?

like image 298
Bartek S Avatar asked Feb 17 '26 23:02

Bartek S


1 Answers

The token is a simple JWT format. It can be deconstructed using window.atob() in your browser. You can also grab a polyfill for browsers which don't support atob/btoa methods. The code below is from this gist.

// Helper function to extract claims from a JWT. Does *not* verify the
// validity of the token. 
// credits: https://github.com/firebase/angularFire/blob/master/angularFire.js#L370
function deconstructJWT(token) {
   var segments = token.split(".");
   if (!segments instanceof Array || segments.length !== 3) {
      throw new Error("Invalid JWT");
   }
   var claims = segments[1];
   return JSON.parse(decodeURIComponent(escape(window.atob(claims))));
}

And here is a fiddle that constructs and deconstructs Firebase tokens using this approach, to give you a working example and a simple tool for testing:

http://jsfiddle.net/katowulf/D4YL8/embedded/result/

like image 105
Kato Avatar answered Feb 19 '26 19:02

Kato