Reputation: 3324
I have 2 rails apps.
App1
needs to send data that will be saved by App2
.
I want to know the best way to create a secure API endpoint to do this.
How can i authenticate the requests App1
sends to App2
I have worked with other API's that require verification for the requests, such as Facebook.
With Facebook they send over in the header a token that i am able to calculate and compare to verify the request.
def verify_webhook(request)
sha1 = request.headers["X-Hub-Signature"].gsub("sha1=", "")
digest = OpenSSL::Digest.new('sha1')
request.body.rewind
data = request.body.read
# Calculate a sha1 with the app key and payload from the post request
calculated_hmac = OpenSSL::HMAC.hexdigest(digest, ENV['FB_APP_SECRET'], data)
# Computate hmac and see if verified is true
verified = ActiveSupport::SecurityUtils.secure_compare(calculated_hmac, sha1)
verified
end
I assume the solution is similar but i cant find documentation for what i am trying to do online, i am not too familiar with the terms so i might be searching the wrong things.
Can someone point me in the right direction?
Upvotes: 1
Views: 352
Reputation: 7231
When designing security-related functionality, you should first establish a threat model. This includes getting a good overview of the attack surface - are your applications communicating over the internet or just over the company network? - and making some assumptions about who would be trying to break your application and how much energy they would be willing and able to invest into that.
For low-threat environments, a pre-shared key/secret transferred in a HTTP header as mentioned by @max's comment would be enough: you just provision both applications with a key and send it in a HTTP header on each call - which should of course be made over a TLS-encrypted connection.
If your threat model includes an attacker who might be able to break that TLS-encrypted connection and gleam the pre-shared secret from there, you can take it up a notch and instead of transferring the key itself in the header, create a checksum via a HMAC and compare it on the client - just like in your example with the Facebook SDK. You might also want to add a cryptographic nonce to avoid a replay attack.
Finally, when designing security-related code you'll probably want to have it reviewed by someone who has experience with security as it's very easy to get something wrong and have all your efforts be in vain.
Upvotes: 1