【问题标题】:Unexpected Value exception意外值异常
【发布时间】:2019-08-16 09:11:40
【问题描述】:

我在测试我的 api 时在邮递员中遇到以下错误。它在邮递员中显示苗条的应用程序错误。错误类型:UnexpectedValueException

消息:段数错误

文件:C:\Users\tahmeed\Documents\app-timber-api2\vendor\firebase\php-jwt\src\JWT.php

行:78

需要修改token还是JWT.php?

JWT.php 中的decode.php

public static function decode($jwt, $key, array $allowed_algs = array())
{
    $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;

    if (empty($key)) {
        throw new InvalidArgumentException('Key may not be empty');
    }
    $tks = explode('.', $jwt);
    if (count($tks) != 3) {
        throw new UnexpectedValueException('Wrong number of segments');
    }
    list($headb64, $bodyb64, $cryptob64) = $tks;
    if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
        throw new UnexpectedValueException('Invalid header encoding');
    }
    if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
        throw new UnexpectedValueException('Invalid claims encoding');
    }
    if (false === ($sig = static::urlsafeB64Decode($cryptob64))) {
        throw new UnexpectedValueException('Invalid signature encoding');
    }
    if (empty($header->alg)) {
        throw new UnexpectedValueException('Empty algorithm');
    }
    if (empty(static::$supported_algs[$header->alg])) {
        throw new UnexpectedValueException('Algorithm not supported');
    }
    if (!in_array($header->alg, $allowed_algs)) {
        throw new UnexpectedValueException('Algorithm not allowed');
    }
    if (is_array($key) || $key instanceof \ArrayAccess) {
        if (isset($header->kid)) {
            if (!isset($key[$header->kid])) {
                throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
            }
            $key = $key[$header->kid];
        } else {
            throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
        }
    }

    // Check the signature
    if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
        throw new SignatureInvalidException('Signature verification failed');
    }

    // Check if the nbf if it is defined. This is the time that the
    // token can actually be used. If it's not yet that time, abort.
    if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
        throw new BeforeValidException(
            'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
        );
    }

    // Check that this token has been created before 'now'. This prevents
    // using tokens that have been created for later use (and haven't
    // correctly used the nbf claim).
    if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
        throw new BeforeValidException(
            'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
        );
    }

    // Check if this token has expired.
    if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
        throw new ExpiredException('Expired token');
    }

    return $payload;
}
AuthController.php

        <?php

    namespace App\Controllers\AppodMobile;
    use \Psr\Http\Message\ServerRequestInterface as Request;
    use \Psr\Http\Message\ResponseInterface as Response;
    use \Interop\Container\ContainerInterface as ContainerInterface;
    use \Illuminate\Database\Query\Expression as Raw;

    use App\Models\AppodMobile\Users as Users;
    use Firebase\JWT\JWT;
    use Tuupola\Base62;

    class AuthController
    {
        use \App\CommonFunctions;
        protected $container;

        public function __construct(ContainerInterface $container) {
            $this->container = $container;
        }


        function auth($request,$response)
        {
            $input = $request->getParsedBody();
            $user = Users::select('id','pword')->where('email','=',$input['email'])->first();

            // verify email address.
            if(!$user) {
                $response->withStatus(404);
                return $response->withJson(['error' => true, 'message' => 'User does not exist.'],404);
            }
            // verify password.
            $salt = getenv('TMS_SALT');
            if (!(sha1($salt.$input['password']) == $user->pword)) {
                $response->withStatus(401);
                return $response->withJson(['error' => true, 'message' => 'Password is incorrect.'],401);
            }
            $now = new \DateTime();
            $future = new \DateTime("+120 minutes");
            $server = $request->getServerParams();
            $jti = (new Base62)->encode(random_bytes(16));
            $payload = [
                "iat" => $now->getTimeStamp(),
                // "exp" => $future->getTimeStamp(),
                "jti" => $jti,
                "sub" => $server["PHP_AUTH_USER"]
            ];
            $token = JWT::encode($payload, getenv('JWT_SECRET'), "HS256");
            $data = array(
                'token' => $token,
                'user_id'=>$user->id,
                // appod'expires' => $future->getTimestamp()
            );
            $response->withStatus(200);
            return $response->withJson($data);
        }

    }


【问题讨论】:

  • 一个 JWT 由 3 个段组成,标头、有效负载和签名,以点分隔。所以您的令牌可能格式错误。但这只是猜测,因为您没有提供有关您的请求和令牌的详细信息。我建议阅读 How to Ask 以更好地了解 SO 的工作原理。
  • 我已经编辑了问题。

标签: php firebase jwt slim


【解决方案1】:

您应该使用 Decode Method 中的第三个参数来解决 Uncaught UnexpectedValueException: Algorithm not allowed

下面是代码

<?php;
require('jwt/vendor/autoload.php');
use \Firebase\JWT\JWT;




function generate_token($uid){

    $key = "thiismykey";
    $jwt = JWT::encode($uid, $key);
    echo "JWT Toke = ".$jwt."<br>";

    $decoded = JWT::decode($jwt, $key, array('HS256'));

    echo "After Encode = ".$decoded;

}


//call the funtion
generate_token("santosh");



?>

输出 -

JWT Toke = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.InNhbnRvc​​2gi.ZUyzpLH0FLB9VdRPS2CaQAqM_wKHjXP80moIzL-8u2o 编码后 = santosh

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2014-10-31
    • 2012-04-09
    • 1970-01-01
    相关资源
    最近更新 更多