【问题标题】:Swift Alamofire Getting Token from Refresh Token Request ErrorSwift Alamofire 从刷新令牌请求错误中获取令牌
【发布时间】:2017-12-12 21:02:51
【问题描述】:

我对使用 Alamofire 还是很陌生,但我提出这个要求是在碰壁。我正在使用 GIDSignIn,并成功为用户获取令牌和刷新令牌,范围为 ["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: ";
}

不是很成功。我是否需要以不同的方式配置我的请求,或者获得适当的访问/权限来获取令牌?非常感谢!

【问题讨论】:

  • 老实说,我也很难过。浏览了您的代码,对我来说似乎是正确的。我知道这不能回答您的问题,但我们决定作为一种解决方法是使用 NodeKit,将其安装为 pod,并通过 Node.JS 文件实现我们的 API 调用。我会密切关注解决方案,如果我找到我的解决方案,我也会标记你。

标签: ios swift oauth-2.0 youtube-api alamofire


【解决方案1】:

@BikeshThakur 帮我弄清楚了! URLEncoding.httpBody 成功了!我也不需要任何标题。

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

【讨论】:

    【解决方案2】:

    我的代码这样累了,你还需要检查一下编码类型URLEncoding.httpBody希望它可以帮助

      let headers = [
            "Content-Type": "application/x-www-form-urlencoded"
        ]
    
        Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
    

    【讨论】:

    • URLEncoding.httpBody 有效!非常感谢@Bikesh
    • 如果答案是正确的,那么我的答案很厚,欢迎朋友
    • 我正在等待验证我自己的答案(他们让你等了一天)。我从您那里获取了一些信息并对其进行了修改以解决我的问题,因为我并没有试图撤销令牌或任何东西。如果您想将答案编辑为我的,我不介意验证您的答案,但这并不能直接解决我的问题。
    • 别担心,兄弟只是问答案是否正确,快乐编码!!!
    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 2016-01-05
    • 2017-03-22
    • 1970-01-01
    • 2012-02-16
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多