简体   繁体   English

快速发布到安全的API

[英]Posting to a secure API with swift

I'm trying to post to an API secured with a key (MailGun) with swift but it appears that my key is never utilized as I receive a Forbidden 401 error (Unauthorized - No valid API key provided) according to https://documentation.mailgun.com/api-intro.html#errors 我正在尝试快速发布到使用密钥(MailGun)保护的API,但是根据https:// documentation,由于收到禁止401错误(未授权-未提供有效的API密钥),我的密钥似乎从未使用过.mailgun.com / api-intro.html#errors

I've verified the URL and key are correct by posting using curl, but I am unable to figure out why my key is not used here. 我已经通过curl验证了URL和密钥的正确性,但是我无法弄清楚为什么在这里不使用我的密钥。 I'm hoping someone can point in the right direction as to why this isn't authenticating correctly 我希望有人可以为正确的方向指出正确的方向

My code is as such but I have replaced all the personal info with <>: 我的代码是这样的,但是我用<>替换了所有个人信息:

// 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()

Update: 更新:

Banged away at it for a few hours and I still can't get my head around it. 撞了几个小时,我仍然无法摆脱它。 Maybe I'm not exactly sure what you mean? 也许我不确定您的意思? I can successfully get a response with curl by using: 我可以使用以下方法成功获得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'

I tried inputting it explicitly like so: 我尝试像这样明确输入:

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

It looks to me like the basic auth credentials are never sent? 在我看来,基本身份验证凭据从未发送过? How can I be sure that the fields are "user" and "password"? 如何确定字段为“ user”和“ password”?

After verifying my header appeared to be missing the authentication section of the header I was able to get this working properly with a large HTTP response. 验证我的标头似乎缺少标头的身份验证部分后,我能够通过较大的HTTP响应使其正常工作。 I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road. 我将完整路径放入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()
}

The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value: Mailgun路径在Keys.plist中作为名为mailgunAPIPath的字符串,其值为:

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

Hope this offers a solution to anyone else having issues with MailGun and wanting to avoid a 3rd party solution! 希望这能为其他与MailGun有问题并希望避免第三方解决方案的人提供解决方案!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM