Search code examples
node.jsjwtapp-storeauth0

jsonwebtoken with custom header and claims


Authenticating to Apple App Store Server and I've got headers as follows

{
  alg: "HS256", 
  typ: "JWT",
  kid: kid
}

and claims with values as follows:

{
  iss: issuerID,
  aud: audience,
  ...
}

In the node-jsonwebtoken library I'm trying to sign with the header as payload and claims as options:

jwt.sign(jwtHeader(), key, jwtClaims(), cb)

This ends up throwing exceptions such as Error: "iss" is not allowed in "options". Otherwise, keep getting 401 Unauthorized response. How may I use this library to appropriately sign my header and claims?


Solution

  • When you sign a token with node-jsonwebtoken you normally just get the default header

    {
      alg: "HS256", 
      typ: "JWT"
    }
    

    If you need any extra values in the header, e.g. the key-id kid, you can add them in the options.header object. You need to pass the options object as a third parameter to the sign function:

    const keyId = 123
    const jwtOptions = {
        header: { kid: keyId }
    }
    

    The options object is also the place where you can add the expirations time, set a different signature algorithm (default is HS256) or switch off the auto-generated timestamp iat(issued at).

    const jwt = require('jsonwebtoken');
    
    // define the payload
    const payload = {
        iss: "issuerID",
        aud: "audience"
    }
    
    const keyId = 123
    
    // extra header values can be defined in the header parameter in the options:
    const jwtOptions = {
        expiresIn: 300,      // 300 seconds
        //algorithm: 'HS512',  // only necessary if you want a different value than 'HS256' 
        //notimestamp: true, // don't added timestamp iat (issued at)
        header: { kid: keyId
                }
    }
      
    // pass the options as third parmater (optional)
    const token = jwt.sign(payload, "supersecret", jwtOptions);
    

    result:

    header:
    {
      "alg": "HS256",
      "typ": "JWT",
      "kid": "123"
    }
    
    payload:
    {
      "iss": "issuerID",
      "aud": "audience",
      "iat": 1630044877,
      "exp": 1630044887
    }