Swift集成Strava API遇Bad Request:Redirect URI无效问题求助
解决Strava OAuth在iOS模拟器中redirect_uri无效的Bad Request问题
问题现象
引导用户连接Strava时,打开授权URL后页面返回Bad Request错误,提示redirect_uri无效,错误信息如下:
{ "message":"Bad Request", "errors":[{ "resource":"Application", "field":"redirect_uri", "code":"invalid" }] }
触发错误的请求链接示例:
https://www.strava.com/oauth/authorize?client_id={{clientId}}&redirect_uri=google.com&response_type=code&scope=read_all,activity:read_all,profile:read_all
该问题仅在iOS模拟器中出现,Postman中请求正常。
相关Swift代码
let url: String = "https://www.strava.com/oauth/mobile/authorize?client_id=97936&redirect_uri=google.com%3A%2F%2F\(Keys.fallbackUrl)&response_type=code&approval_prompt=auto&scope=read" guard let authenticationUrl = URL(string: url) else { return } authSession = ASWebAuthenticationSession(url: authenticationUrl, callbackURLScheme: "google.com") { url, error in if let error = error { print("error: \(error.localizedDescription)") } else { if let url = url { print(url) } } } authSession?.presentationContextProvider = self authSession?.start()
已配置可用的Universal Link(Safari输入域名可直接打开APP),最终计划将redirect_uri替换为自定义域名kette.netlify.app。
已尝试的方案
- 在回调URI和重定向URI前添加
https://,导致iOS模拟器崩溃; - 使用
kette.netlify.app以外的其他URL; - 尝试Deep Linking和Universal Links两种方式。
可行解决方案
1. 严格匹配Strava后台的redirect_uri配置
Strava对redirect_uri校验极为严格,必须与开发者后台应用设置中的授权回调域名完全一致:
- 若用Universal Link,redirect_uri需是完整HTTPS格式,比如
https://kette.netlify.app/callback(含具体回调路径); - 开发者后台的"Authorization Callback Domain"字段仅填
kette.netlify.app,不要加协议头; - 测试阶段先硬编码redirect_uri为后台已配置的完整地址,排除变量拼接或编码错误。
2. 正确配置ASWebAuthenticationSession回调
- 使用Universal Link时,
callbackURLScheme参数需设为nil(Universal Link无需自定义scheme); - 若用自定义Deep Link scheme(如
google.com),必须在Xcode的Info.plist中注册:
同时Strava后台的redirect_uri要对应写成<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>google.com</string> </array> </dict> </array>google.com://your-callback-path格式。
3. 用URLComponents构建授权URL(避免编码错误)
手动拼接URL易出现编码问题,建议用URLComponents自动处理编码:
var components = URLComponents(string: "https://www.strava.com/oauth/mobile/authorize")! components.queryItems = [ URLQueryItem(name: "client_id", value: "97936"), URLQueryItem(name: "redirect_uri", value: "https://kette.netlify.app"), // 替换为后台配置的完整地址 URLQueryItem(name: "response_type", value: "code"), URLQueryItem(name: "approval_prompt", value: "auto"), URLQueryItem(name: "scope", value: "read") ] guard let authenticationUrl = components.url else { return } authSession = ASWebAuthenticationSession(url: authenticationUrl, callbackURLScheme: nil) { url, error in // 回调逻辑处理 }
4. 适配iOS模拟器环境
模拟器对Universal Link支持有特殊要求:
- 确保模拟器已登录Apple ID并开启开发者模式;
- 重置模拟器内容和设置后重装APP,清除缓存的链接配置;
- 先在Safari中打开
https://kette.netlify.app确认能跳转至APP,再进行OAuth流程。
5. 排查添加HTTPS后的崩溃问题
添加https://后崩溃多因URL格式或回调逻辑错误:
- 用
URLComponents构建URL,避免手动编码失误; - 在回调中打印
error的完整信息(而非仅localizedDescription),定位崩溃触发点。
内容的提问来源于stack exchange,提问作者Jorge Zapata
相关产品推荐
相关产品推荐

