Last active
December 2, 2016 12:59
-
-
Save Gurpartap/6741116c76970042d22febf473be340f to your computer and use it in GitHub Desktop.
Authorize api request with api key and secret
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Don't store keys in code. Also these aren't the ones to use. | |
let apiKey = "kPz9WCvH4Z" | |
let apiSecret = "f8v4Sq1929Oci6Qr1Y3h40P58emj03G5" | |
let url = NSURL(string: "https://backend.marshmallows.com/api/v1/ping")! | |
let uri = url.path! | |
let dateString = NSDate.RFC1123DateFormatter().stringFromDate(NSDate()) // Current date time. | |
let signature = "\(method.rawValue)+\(uri)+\(dateString)".hmac(.SHA256, key: apiSecret) | |
let authorizationHeader = "hmac \(apiKey):\(signature)" | |
Alamofire | |
.request(method, url.absoluteString, parameters: params, encoding: .JSON, headers: [ | |
"Authorization": authorizationHeader, | |
"Date": dateString | |
]) | |
.responseData() { response in | |
if let error = response.result.error { | |
print("Error: \(error)") | |
} else if response.response?.statusCode == 401 { | |
print(String(data: (response.request?.HTTPBody)!, encoding: NSUTF8StringEncoding)) | |
print("Access forbidden") | |
} else if let data = response.result.value { | |
// it works... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment