Cannot Extend Model To Use HS512 For Token Creation
Closed this issue · 3 comments
I'm trying to use HS512 instead of the default HS256 for creating a jwt. I tried adding the following to my script:
class MyJWT extends \Lindelius\JWT\JWT
{
use \Lindelius\JWT\Algorithm\HMAC\HS512;
}
No errors occur, but it won't use the HS512 algorithm. As a workaround, I modified the StandardJWT.php file and changed all instances of "HS256" to "HS512."
Let me know if you need more information re script/composer config.
Hi @bfailing,
When you're creating the JWT tokens you need to pass the chosen algorithm as the first parameter to the constructor (the StandardJWT class does this for you by overriding the constructor, but with the HS256 algorithm). The traits pulls in the required functionality but does not automatically set which algorithm to use when encoding the JWT.
You may either pass the algorithm when instantiating the JWT
class MyJWT extends \Lindelius\JWT\JWT
{
use \Lindelius\JWT\Algorithm\HMAC\HS512;
}
$jwt = new MyJWT('HS512'); // Set which algorithm to use
$jwt->sub = '007';
// Encode the token using the previously specified algorithm
$token = $jwt->encode(ENCODE_KEY);
or by overriding the constructor
class MyJWT extends \Lindelius\JWT\JWT
{
use \Lindelius\JWT\Algorithm\HMAC\HS512;
/**
* @param string $algorithm
* @param array $header
* @param string|null $signature
*/
public function __construct(string $algorithm = 'HS512', array $header = [], ?string $signature = null)
{
parent::__construct($algorithm, $header, $signature);
}
}
$jwt = new MyJWT();
$jwt->sub = '007';
$token = $jwt->encode(ENCODE_KEY);
When decoding the tokens the library will pick the correct algorithm as long as the alg
header field has the correct value. This is handled automatically, so you shouldn't have to worry about it, but if you have created a token using one algorithm and then change the algorithm, the old tokens won't work.
That makes sense and it works. Please consider including this information in your readme.