Fix JWT Vulnerabilities (Weak Signing, None Algo) in Yii
JWT implementation in Yii2 is frequently compromised by blind trust in the 'alg' header. Attackers exploit the 'none' algorithm support or perform HMAC/RSA confusion to forge identities. If your parser doesn't explicitly enforce the signing key and algorithm constraints, your authentication layer is effectively non-existent. We're going to harden the sizeg/yii2-jwt component against these common bypasses.
The Vulnerable Pattern
use sizeg\jwt\Jwt;// VULNERABLE: Trusting the token without strict algorithm enforcement $authHeader = Yii::$app->request->getHeaders()->get(‘Authorization’); if ($authHeader && preg_match(’/^Bearer\s+(.*?)$/’, $authHeader, $matches)) { $token = Yii::$app->jwt->getParser()->parse((string) $matches[1]);
// DANGER: Only checking if the token exists, not if it was signed with the expected algo // An attacker can set 'alg': 'none' or use a public key to sign an HMAC token $userId = $token->claims()->get('uid'); return User::findOne($userId);
}
The Secure Implementation
To neutralize JWT vulnerabilities in Yii, you must transition from 'parsing' to 'validating'. 1. The 'none' algorithm is blocked by using the `SignedWith` constraint, which forces the library to verify the signature using a specific signer and key regardless of what the token header claims. 2. We use `HS256` (Symmetric) or `RS256` (Asymmetric) explicitly; never allow the client to choose. 3. Ensure your `JWT_SECRET` is high-entropy (min 32-64 bytes) and stored in `.env`, never hardcoded in the `web.php` config. 4. Always include a `StrictValidAt` constraint to prevent Replay Attacks via expired tokens.
use Lcobucci\JWT\Validation\Constraint\SignedWith; use Lcobucci\JWT\Validation\Constraint\StrictValidAt; use Lcobucci\JWT\Clock\SystemClock;$jwt = Yii::$app->jwt; $token = $jwt->getParser()->parse((string) $matches[1]);
// SECURE: Explicitly define constraints to prevent ‘none’ and key confusion $constraints = [ new SignedWith($jwt->getSigner(‘HS256’), $jwt->getKey()), // Force HS256 and use internal secret new StrictValidAt(new SystemClock(new \DateTimeZone(Yii::$app->timeZone))) ];
// Validate against the constraints before accessing claims if (!$jwt->validate($token, …$constraints)) { throw new \yii\web\UnauthorizedHttpException(‘Security Validation Failed: Invalid Signature or Algorithm’); }
$userId = $token->claims()->get(‘uid’);
Your Yii API
might be exposed to JWT Vulnerabilities (Weak Signing, None Algo)
74% of Yii apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.