【问题标题】:Getting token from an asp.net web api in iOS / swift从 iOS / swift 中的 asp.net web api 获取令牌
【发布时间】:2017-02-09 00:55:51
【问题描述】:

我是.net 开发人员,但对iOSswift 开发非常陌生,只需要使用Swift2 使用Web API 的帮助

Asp.net Web API 已使用OAuth2 身份验证构建,并已发布到安装了 SSL 证书的 Azure VM 服务器。 API 站点本身工作正常,通过 Postman 测试

但是,当我开始在 Swift 中编写前几行代码以获取身份验证令牌时,我遇到了困难。在阅读了一些在线教程后,我决定参与Alamofire,并制作了以下代码sn-p:

func GetToken() {

    let params = [
        "grant_type" : "password",
        "username" : "123456@qq.com",
        "password" : "averygoodpassword"
    ]

    let headers = [
        "Content-Type" : "application/x-www-form-urlencoded"
    ]

    request(.POST, "https://api.example.com/token",
        parameters: params,
        headers: headers,
        encoding: .JSON)
        .responseJSON { request, response, result in

            print (request)
            print (response?.description)
            print (result)

            switch result {
            case .Success(let JSON):
                print("Success with JSON: \(JSON)")

            case .Failure(let data, let error):
                print("Request failed with error: \(error)")

                if let data = data {
                    print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
                }
            }

    }

}

它最终在Xcode 中得到以下输出,这似乎不太好。 error = unsupported_grant_type 告诉我请求已发送到服务器,但参数未与请求一起正确发送。我实在想不通原因和解决办法,在网上挖了几天,但仍然感到绝望。有人可以帮忙吗?即使有人可以在没有任何 3rd 方库的情况下提供纯粹的快速解决方案,也会非常有帮助。谢谢!

Xcode 输出:

可选({ 网址:https://api.example.com/token }) 可选(“ { URL:https://api.example.com/token } { 状态代码:400,标头 {\n \"Access-Control-Allow-Headers\" = \"Content-Type\";\n \"Access-Control-Allow-方法\" = \"GET、POST、PUT、DELETE、OPTIONS\";\n \"Access-Control-Allow-Origin\" = \"*\";\n \"Cache-Control\" = \" no-cache\";\n \"Content-Length\" = 34;\n \"Content-Type\" = \"application/json;charset=UTF-8\";\n Date = \"Fri, 2016 年 9 月 30 日 10:30:31 GMT\";\n 过期 = \"-1\";\n Pragma = \"no-cache\";\n 服务器 = \"Microsoft-IIS/8.5\";\ n \"X-Powered-By\" = \"ASP.NET\";\n} }") 成功 JSON 成功:{ 错误=“不支持的授权类型”; }

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    我在尝试将一些在应用程序中实现的自动电子邮件发布到 MailGun 时遇到了类似的问题。

    我能够通过大型 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?
    

    我略微反对使用 3rd 方库,尤其是对于像 http POST 这样的小东西,这对我来说似乎是一个更易于维护的解决方案。无论如何,希望这会有所帮助,如果您有任何问题,请告诉我!

    【讨论】:

    • 这个问题与使用 Alamofire 和 OAuth2 有关。答案应该提供一个使用 Alamofire 的示例,而不是说“反对使用 3rd 方库”
    猜你喜欢
    • 1970-01-01
    • 2020-12-29
    • 2016-02-27
    • 1970-01-01
    • 2023-04-04
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多