Results 1 to 6 of 6

Thread: Where to store JWT secret?

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    10,021

    Where to store JWT secret?

    I have the following file that I use to generate and validate JWT tokens:
    Code:
    <?php
    
    use ReallySimpleJWT\Token;
    
    require_once(__DIR__ . '/../../vendor/autoload.php');
    
    class AuthUtility {
    
        private static $secret = "-removed-";
    
        public static function AssertBearerToken($headers) {
            return isset($headers["Authorization"])
                ? trim(str_replace("Bearer", "", $headers["Authorization"]))
                : null;
        }
    
        public static function GenerateJsonWebToken($userId) {
            $expiration = time() + 3600;
            $issuer = "localhost";
    
            return Token::create($userId, AuthUtility::$secret, $expiration, $issuer);
        }
    
        public static function ValidateJsonWebToken($token) {
            return Token::validate($token, AuthUtility::$secret);
        }
    }
    ?>
    The only thing I'm not certain about is how I'm storing the secret that generates the JWT token. Right now it is a private (static) method in the class, but that doesn't feel right. I feel like I should be storing the secret somewhere else a bit more securely.

    What do y'all suggest?

  2. #2
    PowerPoster kfcSmitty's Avatar
    Join Date
    May 2005
    Posts
    2,248

    Re: Where to store JWT secret?

    Easiest "standard" in PHP is to put information like your secret in a config file that lives outside the document root (typically with a .env file extension) and store the information in there.

    You definitely do not want to hard-code these things in your code as that will usually result in accidental pushes into source control.

  3. #3

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    10,021

    Re: Where to store JWT secret?

    This seems to work for me:
    Code:
    <?php
    
    use ReallySimpleJWT\Token;
    
    require_once(__DIR__ . '/../../vendor/autoload.php');
    
    class AuthUtility {
    
        private static $envFile = __DIR__ . "-path removed-";
    
        public static function getSecret() {
            $secret = "";
    
            $file = fopen(AuthUtility::$envFile, "r");
            $contents = fread($file, filesize(AuthUtility::$envFile));
            fclose($file);
    
            $lines = explode("\r\n", $contents);
            foreach ($lines as $line) {
                $env = explode("=", $line);
                if ($env[0] === "JWT_SECRET") {
                    $secret = $env[1];
                    break;
                }
            }
    
            return $secret;
        }
    
        public static function assertBearerTokenInHeaders($headers) {
            return isset($headers["Authorization"])
                ? trim(str_replace("Bearer", "", $headers["Authorization"]))
                : null;
        }
    
        public static function assertUserIdInHeaders($headers) {
            $secret = AuthUtility::getSecret(); 
            $token = AuthUtility::assertBearerTokenInHeaders($headers);
            $valid = Token::validate($token, $secret);
            $userId = null;
    
            if ($valid) {
                $parse = Token::parser($token, $secret);
                $parsed = $parse->parse();
                $payload = $parsed->getPayload();
                $userId = $payload["user_id"];
            }
    
            return $userId;
        }
    
        public static function assertUserIdInJsonWebToken($token) {
            $valid = Token::validate($token, AuthUtility::$secret);
            $userId = null;
    
            if ($valid) {
                $parse = Token::parser($token, AuthUtility::$secret);
                $parsed = $parse->parse();
                $payload = $parsed->getPayload();
                $userId = $payload["user_id"];
            }
    
            return $userId;
        }
    
        public static function generateJsonWebToken($userId) {
            $expiration = time() + 3600;
            $issuer = "localhost";
    
            return Token::create($userId, AuthUtility::$secret, $expiration, $issuer);
        }
    }
    ?>
    But it just seems inefficient to read the file and parse the lines anytime a request is made.

  4. #4
    PowerPoster kfcSmitty's Avatar
    Join Date
    May 2005
    Posts
    2,248

    Re: Where to store JWT secret?

    Unfortunately that is kinda how PHP works.. it doesn't try to save any state betweeen requests.

    You could use a caching solution like memcache or redis to store the data, but unfortunately that's about the limit of my PHP knowledge.

  5. #5
    Junior Member nihitthakkar's Avatar
    Join Date
    Jan 2021
    Location
    USA
    Posts
    17

    Re: Where to store JWT secret?

    A JWT is store in a safe place inside the user's browser. It is accessible by any script inside your page if stored it inside local Storage.

  6. #6

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    10,021

    Re: Where to store JWT secret?

    @nihitthakkar - I think you may have misunderstood my question. I was not asking where to store the JWT, rather I was asking where to store the secret that generates the JWT.

    I am storing the generated JWT either in localstorage or as a session cookie, depending on how the user logged in.

    But when I need to validate the JWT passed from the front-end via the bearer token, I need to pull in the JWT secret in order to do the validation.

    Right now the JWT secret is stored as a .ENV file that resides outside of the root server directory, so anytime I need to do a validation check I need to read that file to get the secret.

    My concern was that it seems inefficient to read the file anytime a request is made.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width