2016-12-01 135 views
1

处理涉及利用Firebase的JavaScript Web应用程序的项目,该项目涉及到具有受保护功能的PHP文件。从JavaScript发送验证PHP中的Firebase令牌验证码

为了做到这一点,我得到了(JWT)令牌通过调用:

firebase.auth().currentUser.getToken(true) 

全功能的存在:

firebase.auth().currentUser.getToken(true).then(function(idToken) { 

    var uid = firebase.auth().currentUser.uid; 

    var http = new XMLHttpRequest(); 
    var url = "http://localhost/jwt.php"; 
    var params = "token=" + idToken + "&uid=" + uid; 
    http.open("POST", url, true); 

    //Send the proper header information along with the request 
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

    http.onreadystatechange = function() {//Call a function when the state changes. 
     if(http.readyState == 4 && http.status == 200) { 
      alert(http.responseText); 
     } 
    } 
    http.send(params);  

    console.log("TOKEN: " + idToken); 
}).catch(function(error) { 
    // Handle error 
}); 

在PHP端我使用的验证令牌lcobucci/jwt库。

use Lcobucci\JWT\Parser; 
use Lcobucci\JWT\ValidationData; 
use Lcobucci\JWT\Signer\Keychain; 
use Lcobucci\JWT\Signer\Rsa\Sha256; 

$data = new ValidationData(); 
$data->setIssuer('https://securetoken.google.com/<Project ID>'); 

$signer = new Sha256(); 
$keychain = new Keychain(); 

if($_POST["token"]) { 
    $token = (new Parser())->parse((string) $_POST["token"]); 
    $token->getHeaders(); // Retrieves the token header 
    $token->getClaims(); // Retrieves the token claims 

    $kid = $token->getHeader('kid'); 
    $iat = $token->getClaim('iat'); 

    //Grab Google keys 
    $json_url = file_get_contents('https://www.googleapis.com/robot/v1/metadata/x509/[email protected]'); 
    $json = json_decode($json_url, true); 

    $public_key = $json[$kid]; // Matches kid from header to private key provided by Google 


    try { 
     $isTokenValid = $token->verify($signer, $public_key); // Verify token 
    } catch (Exception $e) { 
     $isTokenValid = false; 
    } 

    if($isTokenValid) { 

     echo "Valid"; // Add protected functionality here 

    } else { 
     echo "Invalid"; 
    } 
} 

我的问题是:这是安全的吗?

回答