Thomas McGoey-Smith

Verifying Shopify OAuth Requests in Golang

Right now I’m in the middle of building my first app for Shopify in Go! It’s pretty basic, but I really wanted to try out something simple before I go all in.

Last night I hit a bit of a road block with verifying my oauth requests from Shopify.

On their docs, they point to a simple example in Ruby:

digest = OpenSSL::Digest.new('sha256')
secret = "hush"
message = "code=a94a110d86d2452eb3e2af4cfb8a3828&shop=some-shop.myshopify.com&timestamp=1337178173"

digest = OpenSSL::HMAC.hexdigest(digest, secret, message)
digest == "2cb1a277650a659f1b11e92a4a64275b128e037f2c3390e3c8fd2d8721dac9e2"

I was able to narrow down the package to use in Go (it even came with a nice little verification example).

// CheckMAC returns true if messageMAC is a valid HMAC tag for message.
func CheckMAC(message, messageMAC, key []byte) bool {
	mac := hmac.New(sha256.New, key)
	mac.Write(message)
	expectedMAC := mac.Sum(nil)
	return hmac.Equal(messageMAC, expectedMAC)
}

However, I wasn’t able to get it working.

After a ton of trial and error - and a bunch of research working with HMAC verifications, I was able to track down my problem.

It turns out I just needed to encode my expectedMAC using the hex package.

Now it works!

Here’s the final code that I ended up using:

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

func verifyRequest(expectedHMAC, message, sharedSecret string) bool {
	h := hmac.New(sha256.New, []byte(sharedSecret))
	h.Write([]byte(message))

	return hmac.Equal([]byte(expectedHMAC), []byte(hex.EncodeToString(h.Sum(nil))))
}

func main() {
	hmac := "2cb1a277650a659f1b11e92a4a64275b128e037f2c3390e3c8fd2d8721dac9e2"
	message := "code=a94a110d86d2452eb3e2af4cfb8a3828&shop=some-shop.myshopify.com&timestamp=1337178173"
	sharedSecret := "hush"

	if verifyRequest(hmac, message, sharedSecret) {
		fmt.Println("Valid Request")
	} else {
		fmt.Println("Invalid Request")
	}
}

(Here’s the Playground too)

Hope that saves you some time!

@tamcgoey on Jul 14, 2015

Enjoyed the article? Subscribe to my newsletter for more.

© Thomas McGoey-Smith (2014-2018). RSS.