2 Answers
- Newest
- Most votes
- Most comments
0
Hi Antonio,
Are those solutions to your question ?
- https://www.altostra.com/blog/asymmetric-jwt-signing-using-aws-kms
- https://medium.com/@adisesha/jwt-signature-with-aws-kms-3cb69a97fcdd
Best,
Didier
0
Ciao Antonio,
try this instead:
const AWS = require('aws-sdk');
const jwt = require('jsonwebtoken');
const kms = new AWS.KMS({ region: 'your-region' });
async function signTokenWithKMS(payload) {
// Sign the payload using KMS
const params = {
KeyId: 'your-kms-key-id',
Message: JSON.stringify(payload),
MessageType: 'RAW',
SigningAlgorithm: 'RSASSA_PKCS1_V1_5_SHA_256' // or any other suitable algorithm
};
const { Signature } = await kms.sign(params).promise();
// Convert the KMS signature into a format compatible with jsonwebtoken
const base64EncodedSignature = Signature.toString('base64');
return base64EncodedSignature;
}
async function generateJWTToken(payload) {
try {
const signature = await signTokenWithKMS(payload);
// Use the converted signature with jsonwebtoken
const token = jwt.sign(payload, signature, { algorithm: 'RS256' });
return token;
} catch (error) {
console.error('Error generating JWT token:', error);
throw error;
}
}
// Example usage
const payload = { user: 'user123', role: 'admin' };
generateJWTToken(payload)
.then(token => console.log('Generated JWT token:', token))
.catch(error => console.error('Error generating JWT token:', error));
Differences are:
- The "new" implementation uses the aws-sdk package instead of @aws-sdk/client-kms. This simplifies the dependency management as it relies on the standard AWS SDK for JavaScript/Node.js.
- In the "new" implementation, the signing operation is performed directly through the kms.sign() method from aws-sdk. This eliminates the need to create a SignCommand object explicitly.
- In the "new" implementation, the signature returned by the KMS service is converted to a base64 encoded string, which is then passed as the private key parameter to the jsonwebtoken.sign() function. This is different from the "old" implementation, where the signature is directly encoded using base64url.encode(Buffer.from(res.Signature)).
- Error handling might differ between the two implementations, but it's not explicitly shown in the provided code snippets. These differences highlight a shift in how the KMS signing operation is integrated into the JWT token generation process, moving towards a more streamlined approach by leveraging the capabilities of the aws-sdk and jsonwebtoken libraries directly.
Relevant content
- asked 3 years ago
- asked a year ago
- asked 2 years ago
- asked 10 months ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 2 years ago
I saw both of them, but first one does not seem to be working correctly and second articleis a different language implementation. Tried to "translate" it into Javascript but didnt work.