stripe-node icon indicating copy to clipboard operation
stripe-node copied to clipboard

Webhook signature validation not working

Open rshov opened this issue 9 years ago • 30 comments

Hi, I'm using the latest version of the stripe node.js library v4.19.0 and am trying to verify the signature in some test webhooks. It is failing with:

error: Error SyntaxError: Unexpected token o in JSON at position 1 at Object.parse (native) at Object.Webhook.constructEvent (C:\Users\shovl\BitBucket\apm-billing\node_modules\stripe\lib\Webhooks.js:10:28)

I followed the example here: https://github.com/stripe/stripe-node/blob/master/examples/webhook-signing/express.js

Does the node.js library officially support webhook signatures yet? I noticed that the documentation does not list Node.js when referring to the "official" libraries.

Thanks very much, Raymond

rshov avatar May 12 '17 15:05 rshov

@rshov The error is indicating that the contents of the rawBody aren't valid JSON; can you add console.log('req.rawBody', req.rawBody); at line 32 of express.js and provide me with the output?

Also, when you say 'test webhooks,' do you mean you're:

  • Creating stuff in your Test environment and handling the webhooks;
  • Sending a Test Webhook from the Dashboard; or
  • Something else?

Also ... I should make that error more informative. :) Will work on that!

jlomas-stripe avatar May 12 '17 15:05 jlomas-stripe

@jlomas-stripe Looks like the problem was I had an older version of the body-parser package in my app. Once I updated that to the latest version v1.17.1 it is working well. The older version must not have saved the raw body correctly. Your example works just fine. Thank you for the quick followup!

rshov avatar May 12 '17 17:05 rshov

Awesome - glad to hear it! \o/

jlomas-stripe avatar May 15 '17 16:05 jlomas-stripe

I'm having the same problem. I have latest Stripe (4.23.1) and Body-praser (1.17.2),. the request.rawBody is Empty. and the request.body show something weird in data.object:

data: { object: { object: 'invoice', amount_due: 0, forgiven: false, lines: [Object],

lines is [Object] ?

murvinlai avatar Jul 07 '17 10:07 murvinlai

I was also seeing this.
In my code I was using bodyParser before handling off to stripe, this seems to have caused it.

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// was handling other routes here
app.get('/foo', bar)

app.post('/stripe/webhooks', stripeWebhooks)

Solution was to remove the bodyParser functions here in my main route, moving these into modules with use. Each module can now set its own bodyParser requirements.

app.use('/stripe', stripeWebhooks)

tim-field avatar Jul 12 '17 02:07 tim-field

I fixed that in my code. The problem is that I didn't follow the instruction and using wrong bodyParser format:

It should be: app.use(require("body-parser").raw({type: "*/*"}));

once change that, it works for me. In addition, instead of app.use() and define as global for all routes. I just use the bodyParser as middleware so I can have different bodyParser for different route.

murvinlai avatar Jul 12 '17 04:07 murvinlai

I ran into this today to. Like others, the fix is to provide constructEvent with a JSON string instead of a parsed object.

Rather than modifying application code, would it make more sense to allow the constructEvent method to accept either raw JSON or an Object?

atomdmac avatar Jul 12 '17 22:07 atomdmac

@atomdmac Unfortunately, that's not possible. The signature is calculated based on the raw JSON that we send you. If you parse it in your system you can not easily get back to the exact same string which would be required to compare the signatures. That's why it's important that your code sends the exact raw string that we sent you.

remi-stripe avatar Jul 12 '17 22:07 remi-stripe

@remi-stripe Thanks for your reply! I was actually just struggling to figure out why my payloads weren't validating when I converted them back to a string with JSON.stringify().

atomdmac avatar Jul 12 '17 23:07 atomdmac

I struggled with this for sometime with a FirebaseFunctions backend. This issue helped me diagnose, so I'lll post this for anyone else who stumbles in here with the same issue. Firebase functions does not currently have a way to access unparsed JSON body https://issuetracker.google.com/issues/36252545

Anyone have a workaround?

mattxgreen avatar Jul 15 '17 16:07 mattxgreen

@mattxgreen As mentioned in the Google issue there, there's unfortunately no way to do this at present, so I don't think you'll be able to use Webhook Signature verification with Stripe Webhooks until there's a way to get at the raw body there, as without having access to the raw body, you can't really properly verify this.

jlomas-stripe avatar Jul 31 '17 22:07 jlomas-stripe

Thanks for the info everyone. For others, I also solved it this way:

app.post('/stripe_event', require("body-parser").raw({type: "*/*"}), stripeEvent)

I had to remove/move my other calls to require("body-parser") further up the line as well

bentedder avatar Sep 22 '17 02:09 bentedder

For anyone coming here with a firebase functions setup as @mattxgreen mentioned, fyi this fix is in place now and you can just use

req.rawBody

As first argument to constructor without any additional parsing etc

Much appreciated, thank you @SamMatthewsIsACommonName! I was struggling with this for a bit.

nickjanssen avatar Jun 01 '18 07:06 nickjanssen

For those of you struggling with this because you set bodyParser.json() as the default parser for your 'application/json' routes in a config somewhere, overriding it in a route later on like below will NOT work.


const express = require('express')
const router = express.Router()
const bodyParser = require('body-parser')
const rawParser = bodyParser.raw({type: "*/*"})
/**
Some application routes
**/
router.post('/stripe/webhook', rawParser, function (req, res) { })  

Instead, you can set this in your config file like so and then set the rest of the 'application/json' routes to use the JSON body parser. Make sure to update '/stripe/webhook' to the path of your webhook route and make sure to include this line before you declare bodyParser.json() for the rest of your 'application/json' routes.


/**
Some global config file for your application
**/
app.use('/stripe/webhook', bodyParser.raw({type: "*/*"}))
app.use(bodyParser.json({type: 'application/json'}))

Personally, I think it would be a huge pain to not set a default parser for your JSON requests and to manually set the parser type for each route as some have suggested. Hope this helps!

tomchomiak avatar Oct 05 '18 05:10 tomchomiak

If you really want to get fancy then you can use a regular expression or some wild card expression in your config file like so.


/**
Some config file for your application
**/
app.use('*/raw-json/*', bodyParser.raw({type: "*/*"}))
app.use(bodyParser.json({type: 'application/json'}))

Any routes that have '/raw-json/' in their path will use bodyParser.raw() and the rest of your routes that accept 'application/json' will get a parsed JSON body.


const express = require('express')
const router = express.Router()
/**
Some application routes
**/
router.post('/stripe/raw-json/webhook', function (req, res) { /* Gets raw json body */ })  
router.post('/stripe/webhook', function (req, res) { /* Gets parsed json body */ })  

tomchomiak avatar Oct 05 '18 05:10 tomchomiak

Was having this issue just now, my solution was to put the raw body parse before the json parser. No need to assign it to custom routes, and it doesn't affect my existing endpoints. e.g.

app.use(bodyParser.raw({type: "*/*"}))
app.use(bodyParser.json())

vivaldi-va avatar Nov 18 '18 20:11 vivaldi-va

Having the same issue, no matter what i do i cant verify, as json string, as object, nothing works.

const bodyParser = require('body-parser');
const rawParser = bodyParser.raw({type: "*/*"});

router.post("/webhook", rawParser, async (req, res) => {

My app currently uses this middleware.

app.use(express.json());
app.use(cors());
app.use(cookieParser());
app.use(express.urlencoded({extended: true}));
app.use(express.static("public"));
app.use(helmet());

UPDATE: Fixed, Strip it of all middleware, use bodyParser alone.

app.use("/webhook", bodyParser.raw({type: "*/*"}), route_webhook);
app.use(express.json());
app.use(cors());
app.use(cookieParser());
app.use(express.urlencoded({extended: true}));
app.use(express.static("public"));
app.use(helmet());

markmorris avatar Mar 05 '20 16:03 markmorris

Like @SamMatthewsIsACommonName said, the solution for firebase cloud functions is something like this here below to change it to req.rawBody.

app.post(
  "/stripe-webhook",
  bodyParser.raw({ type: "application/json" }),
  async (req: any, res: any) => {
    let event;
    try {
      event = stripe.webhooks.constructEvent(
        req.rawBody,
        req.headers["stripe-signature"],
        constants.STRIPE_WEBHOOK_SECRET
      );
    } catch (err) {
      console.log(err);
      console.log(`⚠️  Webhook signature verification failed.`);
      console.log(
        `⚠️  Check the env file and enter the correct webhook secret.`
      );
      return res.sendStatus(400);
    }
...

This article also explains it well if someone wants to read more: https://medium.com/@GaryHarrower/working-with-stripe-webhooks-firebase-cloud-functions-5366c206c6c

maakle avatar May 27 '20 00:05 maakle

As of Express 4.16 +, bodyParser is now deprecated.

Stack Overflow on this

It's been pulled back into Express.

You can now use express in place of bodyParser.

Also, as of Express 4.17.1, there is an express.raw that you can use in place of bodyParser.raw.

So, with those substitutions in Express 4.17.1, this is working for me (combining some of the solutions above with bodyParser).

. . . 
app.use('/webhook/stripe', express.raw({ type: "*/*"}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: false }));
. . .

I hope that helps others save the few hours I lost banging my head on this.

curtiskeisler avatar Apr 10 '21 02:04 curtiskeisler