Signing API Requests via HMAC
Ingredients of Authenticated Request
API Secret Key (aka Private Key)
API Access Key (aka Public Key)
API Endpoint
Timestamp
Signature
Custom Headers
Process of Authenticating a Request
Concatenate API Endpoint
[3] and Timestamp
[4] to create a new string
Create the Signature
[5] by calculating the HMAC
of this string using the API Secret
[1]
Make a request to this endpoint by attaching some parts to the Custom Headers [6]:
Magpie-Access-Key
Magpie-Signature
Magpie-Timestamp
curl -X GET \
-H " Magpie-Access-Key: FGHIJ67890" \
-H " Magpie-Signature: a968473cfe470d0df23d7911e76b" \
-H " Magpie-Timestamp: 2015-01-02 01:02:03" \
http://api.magpie.im/v1/customers/
Calculating the Signature
import hashlib , hmac
def sign (secret_key , endpoint , timestamp ):
msg = '%s %s' % (endpoint , timestamp )
digest = hmac .new (secret_key , msg , hashlib .sha256 ).hexdigest ()
return digest
secret_key = 'ABCDE12345'
endpoint = '/v1/customers/'
timestamp = '2015-01-02 01:02:03'
signature = sign (secret_key , endpoint , timestamp )
import javax .crypto .Mac ;
import javax .crypto .spec .SecretKeySpec ;
public String sign (String secret , String endpoint , String timestamp ){
String message = endpoint + " " + timestamp ;
Mac mac = Mac .getInstance ("HmacSHA256" );
mac .init (new SecretKeySpec (secret .getBytes (), "HmacSHA256" ));
String digest = new String (Hex .encodeHex (mac .doFinal (message .getBytes ())));
return digest
}
#import < IGDigest/NSString+SHA256HMAC.h>
- (NSString *)signatureWithSecret:(NSString *)secret endpoint:(NSString *)endpoint timestamp:(NSDate *)timestamp
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc ] init ];
[dateFormatter setDateFormat: @" YYYY-MM-dd HH:mm:ss" ];
NSString *timestampFormatted = [dateFormatter stringFromDate: timestamp];
NSString *message = [NSString stringWithFormat: @" %@ %@ " , endpoint, timestampFormatted];
NSString *digest = [message SHA256HMACWithKey: secret];
return digest;
}