Reputation: 73
I need a token to authenticate to a server, I am using jsonwebtoken
, but it will only work if the header of the token is
{
"alg": "RS256"
}
and not
{
"alg": "RS256",
"typ": "JWT"
}
and jsonwebtoken
default header is the second one, I tried to set the header in with option as explained here https://github.com/auth0/node-jsonwebtoken
, but there is no example so maybe I am doing it wrong, but noTimestamp
option is working so...
There is this line in doc "The header can be customized via the options.header object." , i think that the point I don't get.
jwt.sign(payload,
pvtKey,
{ algorithm: 'RS256', noTimestamp : true, header: {"alg": "RS256"} }, function(err, token) {
if (err) {
return res.status(500).send("Error1: "+ err);
}
console.log("Created token: " + token);
});
but it just doesn't change anything so if someone know how to set headers?
thanks in advance
Upvotes: 6
Views: 6690
Reputation: 22555
The function jwt.sign()
creates a default header like this:
{
"alg": <algorithm>,
"typ": "JWT"
}
If a header
parameter is present, a header will be created that contains additional key/value pairs according to the parameter. If the parameter contains a different value for typ
or alg
, the value from the parameter will be taken. And, as mentioned in the answer by Atul, if you set the value to undefined
, you can also get rid of the standard header.
In the following example, I remove the typ
key by setting it undefined
and add an extra key x
:
jwt.sign(payload, pvtKey,
{ algorithm: 'RS256', noTimestamp : true, header: {"typ": undefined, "x":"y"} })
The result is this header:
{
"alg": "RS256",
"x": "y"
}
Conclusion: it works, you can customize your header and also remove standard values (as pointed out by Atul in their answer)
Upvotes: 2
Reputation: 2310
If you want to remove a default value from the header you could also just set undefined
for example:
jwt.sign({ "hello": "world" }, key, { algorithm: "none", header: { typ: undefined } })
produces a jwt which has
payload:
{
"hello": "world",
"iat": 1627481195
}
and signature
{
"alg": "none"
}
Upvotes: 5
Reputation: 5
var h = {"alg":"PS256", "typ":"unknown", "kid":"5FZT6gTLM5wEoSGn3eW0Q8zCPsQ"};
var i = 'ClientId';
var s = 'ClientId';
var a = 'bla';
var signOptions = {
issuer: i,
header: h,
subject: s,
audience: a,
expiresIn: "1h"
};
var token = jwt.sign(payload, privateKEY, signOptions);
results in this header:
{
"alg": "PS256",
"typ": "unknown",
"kid": "5FZT6gTLM5wEoSGn3eW0Q8zCPsQ"
}
Upvotes: -1