ios - Swift Alamofire 从刷新 token 请求错误中获取 token

标签 ios swift oauth-2.0 youtube-api alamofire

我对使用 Alamofire 还很陌生,对于这个请求,我的头撞墙了。我正在使用 GIDSignIn,并成功地为用户获取 token 和刷新 token ,范围为 ["https://www.googleapis.com/auth/youtube.readonly "]。

我正在尝试完成此请求,如 site 上的示例所示.该网站说要忽略对 iOS 使用 client_secret,我这样做了。

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token

下面是我如何使用 Alamofire 实现它。我的 client_id 是 GoogleService-Info.Plist 中 CLIENT_ID 键的值,一个以 .apps.googleusercontent.com 结尾的字符串。 refresh_token 似乎也具有我在网上看到的其他示例的正确格式。

let endpoint = "https://www.googleapis.com/oauth2/v4/token"
let parameters = [
    "client_id" : client_id, 
    "refresh_token" : refresh_token, 
    "grant_type" : "refresh_token"
]

Alamofire.request(endpoint, method: .post, 
                  parameters: parameters, 
                  encoding: JSONEncoding.default)

        .responseJSON { (data) in
            print("data: \(data)")
            let json = JSON(data.result)
        }

数据响应为

data: SUCCESS: {
    error = "unsupported_grant_type";
    "error_description" = "Invalid grant_type: ";
}

不是很成功。我是否需要以不同方式配置我的请求,或获得适当的访问/许可才能获取 token ?非常感谢!

最佳答案

@BikeshThakur 帮我弄明白了! URLEncoding.httpBody 成功了!我也不需要任何 header 。

Alamofire.request(endpoint, method: .post, 
                  parameters: parameters, 
                  encoding: URLEncoding.httpBody)

关于ios - Swift Alamofire 从刷新 token 请求错误中获取 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44989836/

相关文章:

ios - 如何使用 swift 在 ios 设备上发送自动电子邮件?

javascript - 每次我的页面刷新时更新照片

ios - 我该如何解决 Could not cast value of type 'UINavigationController'

java - Spring OAuth2 刷新 token 在刷新访问 token 后更改

ios - 当 block 中的 weakSelf 为 nil 时,什么时候应该添加 strongSelf

ios - 在 iOS 10 中动态调整 AVPlayer 的大小

ios - 如何替换捆绑文件的内容

ios - 如何将数据(从服务器获取)传递到 UIView 中的 tableView

android - Oauth 2 无法为访问 token 交换代码,返回 "invalid_grant"

express - 在同一浏览器上同时访问两个应用程序模块且用户尚未登录时授予提供者 OAuth 状态不匹配