【问题标题】:Swift API Gateway key authorizatiionSwift API Gateway 密钥授权
【发布时间】:2018-03-19 20:39:48
【问题描述】:

我在我的 API 中添加了一个 key,但我很难在我的应用程序代码中实现它。我不断收到message = Forbidden;

我测试了不同的方法,但没有一个有效。这里有什么问题?

if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {

        let url = NSURL(string: "\(APIAddress)")!
        let request = NSMutableURLRequest(url: url as URL)

        request.httpMethod = "PATCH"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("\(APIKey)", forHTTPHeaderField: "Authorization")
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
            if error != nil {
                print(error?.localizedDescription as Any)
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                if let parseJSON = json {
                    let resultValue = parseJSON["success"]
                    print("result: \(String(describing: resultValue))")
                    print(parseJSON)
                }
            } catch let error as NSError {
                print(error)
            }
        }
        task.resume()
    }

请注意该方法在激活 API Gateway 上的 API 密钥之前有效

【问题讨论】:

    标签: swift api amazon-web-services key aws-api-gateway


    【解决方案1】:

    您没有包括 POST 请求所需的所有标头。

    Here're the docs on how to construct a valid request

    您似乎缺少 hostx-amz-date 标头。

    【讨论】:

    • 在将 auth key 添加到 API 之前,该方法运行良好
    • 好吧,我很抱歉你是对的,当使用 PATCHAuthorization header 时,我需要另外 5 个标头。
    • 太棒了! Content-TypeAuthorizationhostx-amz-dateContent-Length?
    • 几乎! "Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header。你有任何使用 Swift 的 API Gateway 的经验吗?
    • 一点点,如果您遇到问题,我建议使用他们的 pod:cocoapods.org/pods/AWSAPIGateway
    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2018-03-20
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多