Hardcoded secrets, unverified tokens, and other common JWT mistakes

Examining 2,000+ npm modules for common mistakes when using JWT

JWT (JSON Web Token) is an open standard (RFC 7519) that defines a way to provide information within a JSON object between two parties. This standard is intended to help transmit information securely, but no standard or technology will protect you when used improperly.

To identify what can go wrong when using JWT in Node.js, I performed a security review on npm modules that use the most popular JWT libraries. Using static analysis tooling, I examined 2,000 npm modules for security weaknesses and vulnerabilities. This post summarizes some common mistakes that were found during my research, including:

  • Hardcoded secrets

  • Allowing the none algorithm for signing

  • Missing or incorrect token validation

  • Sensitive data exposure

In addition to describing these issues so you can avoid them, this post includes open source rules that make it easier to either manually audit your code bases to detect them, or include in CI so these vulnerabilities never get merged into your code in the first place.

Hardcoded secrets

The most basic mistake is using hardcoded secrets for JWT generation/verification. This allows an attacker to forge the token if the source code (and JWT secret in it) is publicly exposed or leaked.

Not only does this introduce a vulnerability, itโ€™s also considered a software anti-pattern. You should keep your JWT secrets apart from your code, for example, in separate configuration files or environment variables.

1const jwt = require("jsonwebtoken");
2const secret = "hardcoded-secret-here"; // ๐Ÿ˜ˆ๐Ÿ˜ˆ๐Ÿ˜ˆ
3
4class JwtAuthentication {
5  static sign(obj) {
6    return jwt.sign(obj, secret, {});
7  }
8}

Itโ€™s worth mentioning that a popular way to use JWTs is within other libraries, e.g., through Passport, a popular authentication middleware for Node.js.

1var JwtStrategy = require('passport-jwt').Strategy,
2    ExtractJwt = require('passport-jwt').ExtractJwt;
3
4var opts = {
5    secretOrKey:'hardcoded-secret-here'; // ๐Ÿ˜ˆ๐Ÿ˜ˆ๐Ÿ˜ˆ
6}
7
8passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
9    // code
10}));

Even though this is a known and quite obvious issue, itโ€™s still common to use hardcoded secrets while developing and then accidentally leave it in your codebase. Fortunately, itโ€™s also very easy to find hardcoded secrets with SAST tools, especially with Semgrep, which helps to find complex code patterns with rules that are very simple to write. Rules for detecting hardcoded secrets:

https://semgrep.dev/editor?registry=javascript.jsonwebtoken.security.jwt-hardcode

https://semgrep.dev/editor?registry=javascript.passport-jwt.security.passport-hardcode

https://semgrep.dev/editor?registry=javascript.express.security.express-jwt-hardcoded-secret

Allowing 'none' algorithm for signing

Allowing tokens to have the 'none' algorithm was a critical vulnerability some years ago. Nowadays, most popular JWT libraries do not allow decoding or verifying tokens with the None algorithm without explicitly enabling it. The same as with hardcoded secrets, itโ€™s easy to leave โ€˜'none'` in your codebase after testing or debugging.

1let jwt = require("jsonwebtoken");
2let secret = "some-secret";
3jwt.verify("token-here", secret, { algorithms: ["RS256", "none"] }); // ๐Ÿ˜ˆ 'none' allowed

Anyway, if you forget to remove it after messing with code, itโ€™s also very easy to catch it with Semgrep. Rules for detecting โ€˜noneโ€™ algorithm allowed in your code:

https://semgrep.dev/editor?registry=javascript.jose.security.jwt-none-alg

https://semgrep.dev/editor?registry=javascript.jsonwebtoken.security.jwt-none-alg

Not verifying tokens the right way

Sometimes developers rely on their methods of token verification instead of using built-in API, or omit verification completely. Small wonder that usually it introduces the opportunity for attackers to forge information inside the token.

1const jwt = require("jsonwebtoken");
2
3const checkToken = (token, refreshToken, key) => {
4  if (jwt.verify(refreshToken, key)) {
5    // ๐Ÿ˜ˆ only `refreshToken` verified
6    return jwt.decode(token).param === jwt.decode(refreshToken).param;
7  }
8  return false;
9};

Note: only refreshToken is verified in the example above, which gives an opportunity to attacker to manipulate function results. By changing value of param property stored inside token an attacker can force the result of checkToken function to be true and pass the verification.

On top of that, itโ€™s very typical to get certain data from tokens before verifying it (issue date, id, etc.) and then use it as a verification context. Usually itโ€™s harmless, but only if this data does not go any further. If the information from an unverified token is passed to other parts of the code it may introduce a vulnerability.

1// token verification logic
2const jwt = require("jsonwebtoken");
3function checkToken(token) {
4  const issuer = jwt.decode(token).issuer;
5  if (findIssuer(issuer) && jwt.verify(token, key)) {
6    // code here
7  } else {
8    throw new Error("not valid token");
9  }
10}
11
12// database utility from different module
13function findIssuer(iss) {
14  // ...
15  database.find(iss);
16}

(In the example above, the unverified issuer value is passed to another function before validating the token (https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A1-Injection). If not used carefully it may end up in different kinds of injection vulnerabilities, especially if located in separate parts of the codebase.)

Also do not forget that even if a token is verified properly, the data stored in it should be treated as user input and be validated and sanitized according to the context.

Rule that helps identify lack of token verification:

https://semgrep.dev/editor?registry=javascript.jsonwebtoken.security.audit.jwt-decode-without-verify

Sensitive data exposure

When an object is converted to a JWT token without explicitly breaking it down into parts, itโ€™s very easy to lose control of what is inside the object and disclose some sensitive information.

This is a very widespread mistake while using ORM libraries like Mongoose, Sequelize, etc. ORM models do not include any sensitive data at the moment of creation, but when the situation changes it is very easy to forget that the ORM object is also passed to JWT token.

1// Mongoose model
2const mongoose = require('mongoose'),
3Schema = mongoose.Schema;
4
5const schema = new Schema({
6    name: String,
7    password: String,
8    admin: Boolean
9});
10
11const User = mongoose.model('LocalUser', schema);
12
13// Express controller
14router.post('/signin', (req,res) => {
15
16User.findOne({name: req.body.name}, function(err, user){
17    var token = jwt.sign(user, key, {expiresIn: 60*60*10}); // ๐Ÿ˜ˆ passing User object directly to JWT
18    res.json({
19        success: true,
20        message: 'Enjoy your token!',
21        token: token
22    });
23});
24
25}

Needless to say, you should not keep sensitive data in JWT token intentionally.

Helpful Semgrep rules:

https://semgrep.dev/editor?registry=javascript.jsonwebtoken.security.audit.jwt-exposed-data

https://semgrep.dev/editor?registry=javascript.jose.security.jwt-exposed-credentials

https://semgrep.dev/editor?registry=javascript.jsonwebtoken.security.jwt-exposed-credentials

These are the most common mistakes developers make when using JWT in their Node.js projects. Stay secure and donโ€™t forget to automate security scans in your codebase.

Resources

More insight on JWT security and best practices:

About

Semgrep Logo

Semgrep lets security teams partner with developers and shift left organically, without introducing friction. Semgrep gives security teams confidence that they are only surfacing true, actionable issues to developers, and makes it easy for developers to fix these issues in their existing environments.

Find and fix the issues that matter before build time

Semgrep helps organizations shift left without the developer productivity tax.

Get started in minutesBook a demo