SwiftUI集成LinkedIn API登录遇invalid_scope_error问题求助
我是一名初级开发者,正在iOS SwiftUI应用中实现基于LinkedIn凭证的登录功能,目前在OpenID Connect的处理上遇到困难。运行应用时出现invalid_scope_error,错误URL显示未知scope:r_liteprofile r_emailaddress w_member_social openid。同时我在LinkedIn开发者平台找不到Sign In with LinkedIn的相关指引,希望得到帮助。
错误信息
错误URL:
https://loginsample152.com/auth/linkedin/callback?error=invalid_scope_error&error_description=Unknown+scope+%26quot%3Br_liteprofile%2520r_emailaddress%2520w_member_social%2520openid%26quot%3B&state=xyz123
出错代码段
if url.absoluteString.hasPrefix("redirect_uri") { decisionHandler(.cancel) // Handle the URL and extract authorization code if let code = extractCode(from: url) { print("Authorization code: \(code)") // Potentially exchange code for token here } } else { decisionHandler(.allow) }
当前实现代码
import SwiftUI struct LogInView: View { var authorizationUrl: URL { let scopes = "r_liteprofile r_emailaddress w_member_social openid" // Correct space-separated scopes let encodedScopes = scopes.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" var components = URLComponents(string: "https://www.linkedin.com/oauth/v2/authorization")! components.queryItems = [ URLQueryItem(name: "response_type", value: "code"), URLQueryItem(name: "client_id", value: "client_id"), URLQueryItem(name: "redirect_uri", value: "redirect_uri"), URLQueryItem(name: "scope", value: encodedScopes), URLQueryItem(name: "state", value: "random_state") // Example state value ] return components.url! }
var body: some View { VStack { // Using the WebView WebView(request: URLRequest(url: authorizationUrl)) } }
问题原因及解决步骤
1. Scope 格式与权限配置问题
- 你使用的
r_liteprofile、r_emailaddress属于旧版API scope,当前LinkedIn Sign In with OpenID Connect推荐使用新版scope:openid(必须,用于OpenID Connect流程)profile(替代r_liteprofile,获取用户基本信息)email(替代r_emailaddress,获取用户邮箱)
w_member_social是发布内容的权限,若仅做登录验证可直接移除,减少权限申请复杂度。- 需在LinkedIn开发者平台的应用「Products」页面,添加「Sign In with LinkedIn」产品,并确保申请的scope已通过审核。
2. URL编码重复问题
URLComponents会自动处理query参数的编码,手动调用addingPercentEncoding会导致重复编码(错误URL中的%2520就是空格被编码两次的结果)。移除手动编码步骤,直接传入原始scope字符串:
let scopes = "openid profile email" // 替换为新版scope // 移除encodedScopes相关代码 components.queryItems = [ URLQueryItem(name: "response_type", value: "code"), URLQueryItem(name: "client_id", value: "你的client_id"), URLQueryItem(name: "redirect_uri", value: "你的redirect_uri"), URLQueryItem(name: "scope", value: scopes), URLQueryItem(name: "state", value: "random_state") ]
3. 回调URL判断逻辑错误
代码中url.absoluteString.hasPrefix("redirect_uri")是错误的,需替换为你实际配置的完整redirect_uri前缀:
let redirectUri = "https://loginsample152.com/auth/linkedin/callback" if url.absoluteString.hasPrefix(redirectUri) { decisionHandler(.cancel) if let code = extractCode(from: url) { print("Authorization code: \(code)") // 后续交换token逻辑 } } else { decisionHandler(.allow) }
4. 找到官方指引
在LinkedIn开发者平台进入你的应用后,点击左侧菜单的「Sign In with LinkedIn」即可查看官方集成指引,包括scope说明、授权流程、token交换等步骤。若找不到该选项,确认已为应用添加「Sign In with LinkedIn」产品。
内容的提问来源于stack exchange,提问作者MARIA VOUNATSOU

