如何在iOS Swift/SwiftUI应用中实现Deezer API的OAuth流程?
Deezer API OAuth授权流程问题解决记录
初始实现
已在Deezer官网创建应用,未使用废弃的Deezer SDK,采用WKWebView加载授权请求:
https://connect.deezer.com/oauth/auth.php?app_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&response_type=token&perms=basic_access
通过WKWebView的导航拦截逻辑捕获重定向,直接从URL中提取token,避免跳转到服务器:
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) { if !isLoading { isLoading = true } if let redirectedUrl = navigationAction.request.url, redirectedUrl.host == AppConfig.redirectHost { // 从URL中提取token let deezerToken = DeezerURLBuilder.deezerToken(fromUrl: redirectedUrl) // 保存token PrefUtils.shared.deezerToken = deezerToken didLogin = true decisionHandler(.cancel) return } decisionHandler(.allow) }
重定向URL格式为:
https://MY_REDIRECT_URL/#access_token=frazeeFRT188maXzvPiCeTDEjCCbrIGGaCwlkGQra4whmp7rtJ&expires=1468
遇到的问题
根据Deezer文档,曾误以为需要先获取code参数,再通过以下请求换取token:
https://connect.deezer.com/oauth/access_token.php?app_id=MY_APP_ID&secret=MY_APP_SECRET&code=THE_MISSING_CODE
直接使用提取的access_token调用用户信息接口:
https://api.deezer.com/user/me?access_token=frazeeFRT188maXzvPiCeTDEjCCbrIGGaCwlkGQra4whmp7rtJ
收到错误:
An active token must be used to query information about the current user
曾推测是iOS WKWebView关闭后无Cookie,而Safari测试正常是因为Cookie留存,但实际并非如此。
问题解决
最终排查发现是URL参数拼写错误,修正后无需服务器重定向,直接使用implicit grant模式(response_type=token)即可正常完成授权并调用接口,无需走code换取token的流程。
内容的提问来源于stack exchange,提问作者fencingCode
相关产品推荐
相关产品推荐

