title: Invalid JWT token causes a 500 internal server error
body: <p>Before the server starts, all plugins etc are registered. I create my strategy and set JWT as default authentication method for the server.</p>
  
  <pre><code>await server.register(require('hapi-auth-jwt2'));
  
  await server.register(require('~/utils/jwt-key-signer'));
  
  server.auth.strategy(
      'jwt', 'jwt',
      { key: process.env.API_KEY,     
      validate: true,  // Temporarily using true          
      verifyOptions: { algorithms: [ 'HS256' ] }
  });
  
  server.auth.default('jwt');
  </code></pre>
  
  <p>Here's my route. I pass the payload from the handler request into a plugin that signs my key and returns a token:</p>
  
  <pre><code>'use strict';
  const Boom = require('boom');
  
  exports.plugin = {
      name: 'user-create',
      register: (server, options) =&gt; {
  
          server.route({
              method: 'POST',
              path: '/user/create',
              options: { auth: 'jwt' },
              handler: async (request, h) =&gt; {
  
                  const { payload } = await request;
  
                  const { JWTKeySigner } = await server.plugins;
                  const token = await JWTKeySigner.signKeyReturnToken(payload);
  
                  const cookie_options = {
                      ttl: 365 * 24 * 60 * 60 * 1000, // expires a year from today
                      encoding: 'none',    // we already used JWT to encode
                      isSecure: true,      // warm &amp; fuzzy feelings
                      isHttpOnly: true,    // prevent client alteration
                      clearInvalid: false, // remove invalid cookies
                      strictHeader: true   // don't allow violations of RFC 6265
                  }
  
  
                  return h.response({text: 'You have been authenticated!'}).header("Authorization", token).state("token", token, cookie_options);
  
              },
              options: {
                  description: 'Creates a user with an email and password',
                  notes: 'Returns created user',
                  tags: ['api']
              }
          });
  
      }
  };
  </code></pre>
  
  <p>Here's how I sign my key:</p>
  
  <pre><code>const jwt = require('jsonwebtoken');
  
  exports.plugin = {
  
      name: 'JWTKeySigner',
      register: (server, options) =&gt; {
  
          server.expose('signKeyReturnToken', async (payload) =&gt; { 
  
              jwt.sign(payload, process.env.API_KEY, { algorithm: 'HS256' }, async (err, token) =&gt; {
  
                  if (err) {
                      console.log(err)
                  } 
  
                  await console.log(`TOKEN${token}`); 
  
                  return token;
              });
  
          })
      }
  };
  </code></pre>
  
  <p>I then visit my route from Postman, then pass my user which contains an email address and password back to the round as JSON, and this is the response I get:</p>
  
  <pre><code>{
      "statusCode": 401,
      "error": "Unauthorized",
      "message": "Missing authentication"
  }
  </code></pre>
  
  <p>Ok, so that proves my route is successfully being protected. I now proceed to add my token into Postman:</p>
  
  <p><a href="https://i.stack.imgur.com/9aamP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9aamP.png" alt="enter image description here"></a></p>
  
  <p>Then I get this error:</p>
  
  <pre><code>{
      "statusCode": 500,
      "error": "Internal Server Error",
      "message": "An internal server error occurred"
  }
  </code></pre>
  
  <p>If I remove the token from postman, I get the "unauthorised" error. </p>
  
  <p>All I'm trying to do is block outside access to my API, and only allow people who have permission to access it. This would be regular users who signup. </p>
  
  <p>When I paste my token into JWT.io, I can see my data on the right hand side of the page, but JWT tells me it's an invalid signature.</p>
  
  <p>I'd really appreciate some clarity here. I'm using hapi-auth-jwt2.</p>
  
  <p>Thanks in advance</p>