【问题标题】:How to get a MS Translator access token from Swift 3?如何从 Swift 3 获取 MS Translator 访问令牌?
【发布时间】:2017-02-27 19:26:12
【问题描述】:

我正在尝试使用 Swift 3 的 MS Translator API(现在在游乐场玩,但目标平台是 iOS)。但是,当我尝试获取 OAuth2 的访问令牌时,我被卡住了。我有以下代码(我试图从Obtaining an access token 的示例中移植代码):

let clientId = "id".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let clientSecret = "secret".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let scope = "http://api.microsofttranslator.com".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

let translatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
let requestDetails = "grant_type=client_credentials&client_id=\(clientId)&client_secret=\(clientSecret)&scope=\(scope)"

let postData = requestDetails.data(using: .ascii)!
let postLength = postData.count

var request = URLRequest(url: URL(string: translatorAccessURI)!)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("\(postLength)", forHTTPHeaderField: "Content-Length")

request.httpBody = postData

URLSession.shared.dataTask(with: webRequest) { (returnedData, response, error) in
    let data = String(data: returnedData!, encoding: .ascii)
    print(data)
    print("**************")
    print(response)
    print("**************")
    print(error)
}.resume()

当然,我使用了有效的 clientId 和有效的 clientSecret。

现在回调打印以下信息。首先,returnedData 包含请求无效的消息,以及以下消息:

"ACS90004: The request is not properly formatted."

其次,响应带有 400 代码(这符合请求格式不正确的事实)。

三、错误为零。

现在我正在使用 Postman 测试调用,当我使用相同的 URI 并将 requestDetails 字符串作为原始正文消息(我手动添加 Content-Type 标头)时,我得到了相同的响应。但是,当我将 Postman UI 中的正文类型更改为 application/x-www-form-urlencoded 并通过其 UI 将请求详细信息作为键值对键入时,调用成功。现在看来,我在消息格式方面做错了,或者甚至是 Swift URLRequest/URLSession API 出现了问题,但是,我无法掌握什么。有人可以帮帮我吗?谢谢。

【问题讨论】:

    标签: ios swift security web oauth-2.0


    【解决方案1】:

    好的,所以经过一些更绝望的谷歌搜索和实验后,我发现了我的错误。为了子孙后代:

    问题在于对 PUT http 请求正文中的参数进行编码。而不是:

    let scope = "http://api.microsofttranslator.com"
                 .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
    

    我必须使用以下内容:

    let scope = "http://api.microsofttranslator.com"
                 .addingPercentEncoding(withAllowedCharacters: 
                             CharacterSet(charactersIn: ";/?:@&=$+{}<>,").inverted)!
    

    似乎API(或HTTP协议,我不是这方面的专家)在请求正文中的/:字符有问题。我必须感谢 Studiosus 在Polyglot issue report 上的回答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-16
      • 2013-03-30
      • 2021-11-10
      • 2023-03-07
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      相关资源
      最近更新 更多