Skip to content

jwt-hardcoded-secret-key

Ensure JWT secret is not hard coded

Storing JSON Web Token (JWT) secret key in the source code (hardcoded) increases significantly the risk that it could be used by an attacker to forge arbitrary valid-looking tokens that would allow to bypass authentication or authorization checks. Consider using an appropriate security mechanism to protect the credentials (e.g. keeping secrets in environment variables). Alternatively, prefer transitioning to using JWTs that are signing using RSA (such as RSA256 algorithm) or EC (such as ES256) Private Keys. The advantage of using RSA or EC is that you do not need to have the secret key simply for verifying the tokens only the matching Public Key is required, which is not sensitive and does not require the same level of protection.

Examples

Insecure Example

package main

import (
    "time"
    "github.com/dgrijalva/jwt-go"
)

func GenerateJWT(userId string) string {
    claims := jwt.StandardClaims{
        Issuer: "server",
        Subject: userId,
        ExpiresAt: time.Now().Unix() + 3600,
    }

    var jwtSigningKey = []byte("super-secret-E47C87FF-48EC-4FB2-ABDA-514CB4B1B365")
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenString, _ := token.SignedString(jwtSigningKey)

    return tokenString
}
package com.bigcorp.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;

public class App
{
    private static String generateJWT(String userId) throws JWTCreationException {
        Algorithm algorithm = Algorithm.HMAC256("super-secret-6FDFBB8F-2909-4565-85EA-3F685784355E");

        String token = JWT.create()
            .withIssuer("server")
            .withSubject(userId)
            .sign(algorithm);

        return token;
    }

    public static void main(String[] args) throws JWTCreationException
    {
        System.out.printf("JWT for Alice: " + generateJWT("Alice"));
    }
}
const jwt = import 'jsonwebtoken';

function generateJWT(userId) {
    const payload = {
        Issuer: "server",
        Subject: userId,
    }
    const token = jwt.sign(payload, "super-secret-6FDFBB8F-2909-4565-85EA-3F685784355E", {algorithm: 'HS256'}));
    return token
}
import datetime
import jwt

def generateJWT(userId):

    #Generate token
    timeLimit= datetime.datetime.utcnow() + datetime.timedelta(minutes=30) #set limit for user
    payload = {"user_id": userId ,"exp":timeLimit}
    return jwt.encode(payload, "super-secret-6FDFBB8F-2909-4565-85EA-3F685784355E")
require 'json/jwt'

def generate_jwt(userid)
    return JSON::JWT.new(payload).sign("super-secret-6FDFBB8F-2909-4565-85EA-3F685784355E", 'HS256')
end

Secure Example

package main

import (
    "time"
    "os"
    "github.com/dgrijalva/jwt-go"
)

func getSigningKey() []byte {
    secret := os.Getenv("JWT_SECRET")
    if (secret == "") {
        panic("JWT_SECRET environment variable not found - aborting")
    }
    return []byte(secret)
}

func GenerateJWT(userId string) string {
    claims := jwt.StandardClaims{
        Issuer: "server",
        Subject: userId,
        ExpiresAt: time.Now().Unix() + 3600,
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenString, _ := token.SignedString(getSigningKey())

    return tokenString
}
package com.bigcorp.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;

public class App
{
    private static String getSigningKey() throws Exception {
        String secret = System.getenv("JWT_SECRET");
        if (secret == null) {
            throw new Exception("JWT_SECRET environment variable not found - aborting");
        }
        return secret;
    }

    private static String generateJWT(String userId) throws Exception {
        Algorithm algorithm = Algorithm.HMAC256(getSigningKey());

        String token = JWT.create()
            .withIssuer("server")
            .withSubject(userId)
            .sign(algorithm);

        return token;
    }

    public static void main(String[] args) throws Exception
    {
        System.out.printf("JWT for Alice: " + generateJWT("Alice"));
    }
}
const jwt = require('jsonwebtoken')
const SECRET = process.env.JWT_SECRET_KEY

function generateJWT(userId) {
    const payload = {
        Issuer: "server",
        Subject: userId,
    }
    const token = jwt.sign(payload, SECRET, {algorithm: 'HS256'}));
    return token
}
import datetime
import jwt

JWT_SECRET = os.getenv('JWT_SECRET')

def generateJWT(userId):
    #Generate token
    timeLimit= datetime.datetime.utcnow() + datetime.timedelta(minutes=30) #set limit for user
    payload = {"user_id": userId ,"exp":timeLimit}
    return jwt.encode(payload, JWT_SECRET)
require 'json/jwt'

jwtsecret = ENV['JWT_SECRET']

def generate_jwt(userid)
    return JSON::JWT.new(payload).sign(jwtsecret, 'HS256')
end