Reddit API的OAuth2错误 - Swift

时间:2018-05-16 00:50:48

标签: swift post oauth alamofire reddit

我正在将Reddit的API集成到我的iOS应用程序中,但是我遇到了一些查询问题。我正在使用Alamofire发出POST请求。当您在已安装的应用上使用Reddit的API时,您必须关注他们的Application Only grant flow。一切正常,除了我收到unsupported_grant_type错误。

这是我的POST请求。

guard let url = URL(string: "https://www.reddit.com/api/v1/access_token") else { return false }
            let params: Parameters = [
                "grant_type" : "https://oauth.reddit.com/grants/installed_client",
                "device_id" : "\(UUID().uuidString)"]

            let username = "MY_CLIENT_ID"
            let password = ""
            let loginString = String(format: "%@:%@", username, password)
            let loginData = loginString.data(using: String.Encoding.utf8)! as NSData
            let base64EncodedString = loginData.base64EncodedString()

            let headers = ["Content-Type" : "application/x-www-form-urlencoded",
                           "Authorization" : "Basic \(base64EncodedString)"]

            Alamofire.request(url, method: .post , parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
                print(response)

            }

我的grant_type参数是否正确?我相信是因为文档告诉我使用https://oauth.reddit.com/grants/installed_client作为已安装应用的授权类型。

1 个答案:

答案 0 :(得分:0)

这对我有用,它不使用AlamoFire。

Swift 4.2

    let ACCESS_TOKEN_URL = "https://www.reddit.com/api/v1/access_token"
    let GRANT_TYPE = "https://oauth.reddit.com/grants/installed_client"
    let DONT_TRACK = "DO_NOT_TRACK_THIS_DEVICE"
    let timeout = 15
    let uncodedClientIDAndPassword = "\(CLIENT_ID):"
    let encodedClientIDAndPassword = uncodedClientIDAndPassword.toBase64()
    let authStr = "Basic \(encodedClientIDAndPassword!)"
    guard let serviceUrl = URL(string: ACCESS_TOKEN_URL) else {
        completionHandler(nil)
        return
    }
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.addValue(authStr, forHTTPHeaderField: "Authorization")

// Important Edit: You need to manually make the parameters, don't make a String dictionary and convert it to JSON and then sending it. Reddit doesn't accept that.
            let param = "grant_type=\(GRANT_TYPE)&device_id=\(DONT_TRACK)"
            let data = param.data(using: .utf8)
            request.httpBody = data
            // timeout
            let config = URLSessionConfiguration.default
            config.timeoutIntervalForRequest = TimeInterval(timeout)
            config.timeoutIntervalForResource = TimeInterval(timeout)
            let session = URLSession(configuration: config)

            session.dataTask(with: request) { (data, response, error) in
                if data != nil {
                    do {
                        if let json = (try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] {
                            self.accessToken = json["access_token"] as? String
                        } else {
                            self.accessToken = nil
                        }
                    }
                }
                completionHandler(self.getAccessToken())
            }.resume()
        }