【问题标题】:Posting to a secure API with swift使用 swift 发布到安全的 API
【发布时间】:2016-10-02 02:25:09
【问题描述】:

我正在尝试通过 swift 发布到使用密钥 (MailGun) 保护的 API,但我的密钥似乎从未被使用,因为我收到了根据 @987654321 的 Forbidden 401 错误(未经授权 - 未提供有效的 API 密钥) @

我已通过使用 curl 发布验证 URL 和密钥是否正确,但我无法弄清楚为什么我的密钥未在此处使用。我希望有人能指出正确的方向,为什么这不能正确验证

我的代码就是这样,但我已将所有个人信息替换为 :

// Email the FBO with desired information
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.mailgun.net/v3/<My Domain>/messages")!)
request.HTTPMethod = "POST"
let data = "from: Excited User <scheduler@<mg.mydomain.com>>&to: [bar@example.com,<my email>]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
request.setValue("key-<my key>", forHTTPHeaderField: "api")
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    if let error = error {
        print(error)
    }

    if let response = response {
        print("url = \(response.URL!)")
        print("response = \(response)")
        let httpResponse = response as! NSHTTPURLResponse
        print("response code = \(httpResponse.statusCode)")
    }
})
task.resume()

更新:

敲了几个小时,我仍然无法理解它。也许我不太确定你的意思?我可以使用 curl 成功获得响应:

curl -s --user 'api:key-<my personal key>' https://api.mailgun.net/v3/mg.<my domain>.com/messages -F from='Reservation Scheduler <scheduler@mg.<my domain>.com>' -F to=reservations@<my domain>.com -F subject='Curl Test' -F text='Test from terminal'

我尝试像这样明确输入:

request.setValue("api", forHTTPHeaderField: "username")
request.setValue("key-<my key>", forHTTPHeaderField: "password")

在我看来,基本身份验证凭据从未发送过?如何确定字段是“用户”和“密码”?

【问题讨论】:

  • 您误读了文档。您需要提供“api”作为用户名和您的密钥作为基本身份验证标头的密码
  • 昨晚和今天早上又花了几个小时,但我仍然无法理解它。发布了更新。可能是凭据没有实际发送吗?看着卷曲它看起来像 api -> 对我来说是关键。我试图明确设置用户名和密码。沮丧,休息一下。
  • 我正在尝试打印会话以便我可以看到请求,但我只收到一个八进制返回。是否可以正确打印请求,以便我可以调试发送到错误位置/根本未发送的内容?
  • 看来是我弄错了,API key 可以单独使用。你试过这个stackoverflow.com/questions/33325137/…
  • 哈哈,是的,这就是让我决定使用 MailGun 的最初问题。现在我相信代码被破坏了,因为它导致了 401 禁止(未经授权 - 没有提供有效的 API 密钥)错误。不知道从这里去哪里。

标签: ios json swift http-post mailgun


【解决方案1】:

在验证我的标头似乎缺少标头的身份验证部分后,我能够通过大型 HTTP 响应使其正常工作。我将完整路径放入 Keys.plist,以便我可以将代码上传到 github,并将一些参数分解为变量,以便以后以编程方式设置它们。

// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?

if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
    keys = NSDictionary(contentsOfFile: path)
}

if let dict = keys {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = dict["mailgunAPIPath"] as? String
    let emailRecipient = "bar@foo.com"
    let emailMessage = "Testing%20email%20sender%20variables"

    // Create a session and fill it with our request
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)

    // POST and report back with any errors and response codes
    request.HTTPMethod = "POST"
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let response = response {
            print("url = \(response.URL!)")
            print("response = \(response)")
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

Mailgun 路径在 Keys.plist 中作为名为 mailgunAPIPath 的字符串,其值为:

https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?

希望这可以为其他有 MailGun 问题并希望避免使用第 3 方解决方案的人提供解决方案!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多