This module allows you to generate JSON Web-Tokens with some elements of the data encrypted and read it in a very simple way, without worry too much about encryption.
npminstall'jwt-token-encrypt'--save
import*asjwtEncryptfrom'jwt-token-encrypt';
Above is a breaking change as before import was done with defaultExport!
Version < "1.0.3"
// Data that will be publicly available
constpublicData={
role:"user"
};
// Data that will only be available to users who know encryption details.
constprivateData={
email:"user",
bank:"HSBC",
pin:"1234",
};
// Encryption settings
constencryption={
key:'AAAAAAAAAAAAAA',
algorithm:'aes-256-cbc',
};
// JWT Settings
constjwtDetails={
secret:'1234567890',// to sign the token
// Default values that will be automatically applied unless specified.
// algorithm: 'HS256',
// expiresIn: '12h',
// notBefore: '0s',
// Other optional values
key:'ThisIsMyAppISS',// is used as ISS but can be named iss too
};
consttoken=awaitjwtEncrypt.generateJWT(
jwtDetails,
publicData,
encryption,
privateData
);
// Encryption settings
constencryption={
key:'AAAAAAAAAAAAAA',
algorithm:'aes-256-cbc',
};
constdecrypted=jwtEncrypt.readJWT(token,encryption);
E.g.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJOS0luVldoQjFyVkxDd3hsdE1OdWlVQzZoOVV1ZEFiaSIsImRhdGEiOnsicHVibGljIjp7ImRhdGExIjoxLCJkYXRhMiI6MiwiZGF0YTMiOjN9LCJlbmNEYXRhIjoiYjliM2QyNDdkNTk4ZTlkODczOTM2NTI4MWVmN2ExZTkifSwiaWF0IjoxNTExMTk5MDg0LCJleHAiOjE1MTEyNDIyODR9.KzfcIY95RR7aPYKn5EcXZYvETDCGZIJ91p7IfXCiClw
Once decoded will hold below contentjwt.io
{
iss:'NKInVWhB1rVLCwxltMNuiUC6h9UudAbi',
data:{
public:{
data1:1,
data2:2,
data3:3
},
encData:'5fb8ed70a3864cbd97b25cc8ca2c0bc7',
},
},
As you can see private data:
privateData={
email:"user",
bank:"HSBC",
pin:"1234",
}
is got encripted and respresented with:
{
....
encData:'5fb8ed70a3864cbd97b25cc8ca2c0bc7',
....
}
To changeencDatalabel you need to pass extra parameter togenerateJWTmethod: e.g.
consttoken=awaitjwtEncrypt.generateJWT(
jwtDetails,
publicData,
encryption,
privateData,
'session',
);
will result in having:
{
iss:'NKInVWhB1rVLCwxltMNuiUC6h9UudAbi',
data:{
public:{
data1:1,
data2:2,
data3:3
},
session:'5fb8ed70a3864cbd97b25cc8ca2c0bc7',
},
},
also to read you will need to pass new filed name
e.g.
// Encryption settings
constencryption={
key:'AAAAAAAAAAAAAA',
algorithm:'aes-256-cbc',
};
constdecrypted=jwtEncrypt.readJWT(token,encryption,'session');