Skip to content

Instantly share code, notes, and snippets.

@ace-subido
Last active December 26, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ace-subido/7218464 to your computer and use it in GitHub Desktop.
Save ace-subido/7218464 to your computer and use it in GitHub Desktop.
Basic Mailgun WebHook ReceiverHere's a basic setup of how to validate an authentic POST to your endpoint from Mailgun Routes.
class ApiController {
protected def getConfig() {
getGrailsApplication().config
}
protected def jsonData(data = null, otherData = null) {
([data: data] + (otherData ?: [:])) as JSON
}
protected def renderUnacceptable() {
response.status = 406
withFormat {
json { render jsonData('Unacceptable') }
}
}
}
import java.security.*
import org.apache.commons.codec.binary.Hex
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
class CryptUtils {
static def validateToken(apiKey, timestamp, token, signature) {
def value = timestamp + token
def mac = Mac.getInstance("HmacSHA256")
mac.init(new SecretKeySpec(apiKey.getBytes('UTF-8'), "HmacSHA256"))
def valueDigest = mac.doFinal(value.getBytes('UTF-8'))
return signature == Hex.encodeHexString(valueDigest)
}
}
class ReceiveController extends ApiController {
static allowedMethods = [
receive: 'POST'
]
def receive() {
if(!CryptUtils.validateToken(
config.mailgun.apiKey,
params.int('timestamp').toString(),
params.token,
params.signature
)) {
renderUnacceptable()
return
}
// .. do your stuff
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment