【发布时间】:2018-12-11 06:28:37
【问题描述】:
当我通过 Alamofire 计算 AWS 签名访问 AWS 网关时。 它响应错误消息“我们计算的请求签名与您提供的签名不匹配。请检查您的 AWS 秘密访问密钥和签名方法。有关详细信息,请参阅服务文档。”
有什么方法可以在 swift 3 中访问 AWS API 网关。如果可能的话,请你给我一些简单的 swift 代码。提前致谢!
private var configuration:AWSServiceConfiguration?
private var awsCredential = AWSCredential()
private func apiGatewaySimple(){
let date = URLRequestSigner().iso8601()
let xAmzStamp = date.short
guard let URL = URL(string: "xxxxx") else { return }
var request = URLRequest(url: URL)
let url = request.url
let host = url?.host
let credentialProvider = AWSCognitoCredentialsProvider(regionType: .APNortheast1, identityPoolId: Constants.IDENTITY_POOL_ID)
let endpoint = AWSEndpoint.init(region: .APNortheast1, service: .APIGateway, url: url)
self.configuration = AWSServiceConfiguration.init(region: .APNortheast1, endpoint: endpoint, credentialsProvider: credentialProvider)
let signer : AWSSignatureV4Signer = AWSSignatureV4Signer(credentialsProvider: self.configuration?.credentialsProvider, endpoint: endpoint)
self.configuration?.requestInterceptors = [AWSNetworkingRequestInterceptor(),signer]
_ = self.configuration?.responseInterceptors
_ = self.configuration?.endpoint
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let requestDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"
_ = dateFormatter.string(from: requestDate)
let params:[String :Any]=["xxx" : "xxx" as AnyObject,
"xxxx" : "xxx" as AnyObject ]
let jsonData = try? JSONSerialization.data(withJSONObject: params, options: [])
let json = jsonData
request.httpMethod = HttpMethod.post.rawValue
request.httpBody = jsonData as! Data
request.setValue(date.full, forHTTPHeaderField: "X-Amz-Date")
request.setValue(self.awsCredential.sessionKey, forHTTPHeaderField: "X-Amz-Security-Token")
request.setValue(json?.count.description, forHTTPHeaderField: "Content-Length")
request.setValue(host, forHTTPHeaderField: "Host")
let contentLength = json?.count
let cfpath = request.url
let query = cfpath?.query
let hash = AWSSignatureSignerUtility.hash(request.httpBody)
let contentsha256 = AWSSignatureSignerUtility.hexEncode(NSString.init(data: hash!, encoding: String.Encoding.ascii.rawValue)! as String)
let canonicalRequest = AWSSignatureV4Signer.getCanonicalizedRequest(request.httpMethod, path: "xxxxx", query: query, headers: request.allHTTPHeaderFields, contentSha256: contentsha256)
let scope = String(format: "%@/%@/%@/%@", xAmzStamp, "ap-northeast-1","execute-api",AWSSignatureV4Terminator)
let signingCredential = String(format: "%@/%@", self.awsCredential.accessKey!,scope)
let awsSignatureSignerV4 = AWSSignatureV4Signer(credentialsProvider: configuration?.credentialsProvider,endpoint:endpoint)
_ = awsSignatureSignerV4?.interceptRequest(request as! NSMutableURLRequest)
let canonicalRequestHash = AWSSignatureSignerUtility.hashString(canonicalRequest)
let stringToSign = String(format: "%@/%@/%@/%@",AWSSignatureV4Algorithm,request.value(forHTTPHeaderField: "X-Amz-Date")!,scope,AWSSignatureSignerUtility.hexEncode(canonicalRequestHash))
let kSigning = AWSSignatureV4Signer.getV4DerivedKey(self.awsCredential.secretKey, date: xAmzStamp, region: "ap-northeast-1", service: "execute-api")
let signature = AWSSignatureSignerUtility.sha256HMac(with: stringToSign.data(using: .utf8), withKey: kSigning)
let credentialsAuthorizationHeader = String(format: "Credential=%@", signingCredential)
let signedHeadersAuthorizationHeader = String(format: "SignedHeaders=%@", AWSSignatureV4Signer.getSignedHeadersString(request.allHTTPHeaderFields))
let signatureAuthorizationHeader = String(format: "Signature=%@", AWSSignatureSignerUtility.hexEncode(NSString.init(data: signature!, encoding: String.Encoding.ascii.rawValue)! as String))
let authorization = String(format: "%@ %@, %@, %@", AWSSignatureV4Algorithm,credentialsAuthorizationHeader,signedHeadersAuthorizationHeader,signatureAuthorizationHeader)
let headers = [
"Content-Type": "application/json" ,
"x-amz-security-token" : self.awsCredential.sessionKey ?? "",
"x-amz-date" : date.full,
"Content-Length" : contentLength?.description ?? "0",
"Authorization" : authorization,
"Host" : host ?? ""
]
Alamofire.request(request).responseString{ (response: DataResponse<String>) in
print("\(response.result.value)")
}
}
【问题讨论】:
标签: ios amazon-web-services swift3 aws-sdk aws-cognito