【问题标题】:Validating Firebase tokens in PHP when sent from JavaScript auth从 JavaScript auth 发送时验证 PHP 中的 Firebase 令牌
【发布时间】:2017-04-15 12:25:05
【问题描述】:

正在处理一个涉及使用 Firebase 的 JavaScript Web 应用程序的项目,该应用程序可以访问带有受保护功能的 PHP 文件。

为了做到这一点,我通过调用获得一个 (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/securetoken@system.gserviceaccount.com');
    $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";
    }
}

我的问题是:这安全吗?

【问题讨论】:

    标签: javascript php firebase jwt firebase-authentication


    【解决方案1】:

    是的,验证这样的令牌签名是安全的。 这将证明令牌内容未使用 Google 的密钥进行修改和签名。

    您可以在此处了解有关 JWT 的更多信息:https://jwt.io/introduction/

    此外,您还可以验证令牌

    $token->validate($data);
    

    这将验证颁发者(iss 声明)和令牌的到期时间(exp 声明) https://github.com/lcobucci/jwt/blob/3.2/README.md

    【讨论】:

      猜你喜欢
      • 2021-10-03
      • 2021-02-06
      • 2017-06-24
      • 2018-12-26
      • 2013-08-19
      • 1970-01-01
      • 2018-07-23
      • 2016-10-04
      • 1970-01-01
      相关资源
      最近更新 更多