如何从 Google YouTube Data API OAuth 2 iOS 获取刷新令牌

Tal*_*ion 5 oauth google-api ios youtube-data-api

我正在使用OAuthSwiftpod 进行 Google API 身份验证。在回调中,刷新令牌丢失。当 Google 返回时500 Server Error,当用户经过身份验证后尝试请求新令牌时,我想存储刷新令牌,并在用户下次登录时授权用户,并检索新令牌。

这是我的代码:

           let callback = "\(Bundle.main.bundleIdentifier ?? ""):/oauth2Callback"
            _ = ytOAuth2Swift?.authorize(
                withCallbackURL: URL(string: callback)!,
                scope: "https://www.googleapis.com/auth/youtube", state: state,
                success: { credential, response, parameters in

                   print("YouTube Access_Token \(credential.oauthToken)")
                    print("YouTube efreshR_Token \(credential.oauthRefreshToken)")
                },
                failure: { error in
                    print("ERROR: \(error.localizedDescription)")
            }
            )
Run Code Online (Sandbox Code Playgroud)

这是我们得到的回复!

响应参数

根据 Google API 文档,这是应该出现的响应:

{
   "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
   "expires_in":3920,
   "token_type":"Bearer",
   "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用嵌入式WebView没有运气:

[嵌入式 WebView 错误消息E[2]

Kar*_*ica 4

好吧,看起来 google API 在开始时给了你一次刷新令牌,而新的请求不再给你了。如果是,您应该知道refresh_token仅在第一次授权时提供,所以如果您授权更多次,它可能不会再次返回refresh_token。请尝试以下说明:

之后,您的下一次调用还应该返回一个刷新令牌

它可能有点不同,因为我在面板中不使用英语。当我使用谷歌的refresh_token时,它永远不会过期,您可以永远使用它来创建新的access_token。

另一种解决方案

如果它不起作用,请尝试在代码中将 access_type 设置为离线(我认为最简单的方法就是在 API url 中添加 GET 参数access_type=offline)。

有需要的也可prompt=consent询问。它将强制用户授权,然后应该返回refresh_token

更多信息可以在Google 文档中找到:Oauth2

提示

Google API 中的一件好事是,refresh_token 永远不会过期,除非您不会撤销它或创建新的令牌。因此,您甚至可以对其进行硬编码,并在每次想要获取新的 access_token 时使用。