我正在尝试使用 iOS/swift 验证 OAuth2 和 Eventbrite。这是我的相关代码片段:
let oauthswift = OAuth2Swift(
consumerKey: Eventbrite["consumerKey"]!,
consumerSecret: Eventbrite["consumerSecret"]!,
authorizeUrl: "https://www.eventbrite.com/oauth/authorize",
accessTokenUrl: "https://www.eventbrite.com/oauth/token",
responseType: "code"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth2-swift://oauth-callback/eventbrite")!, scope: "", state: "",
success: {
credential, response, parameters in
self.showAlertView("Eventbrite", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
但是,当我接受我想要将此应用程序与我的帐户连接后进入 eventbrite oauth 页面时,我在 eventbrite 中看到“哎呀,出了点问题”错误。网址是:https://www.eventbrite.com/oauth/authorize?client_id= {MyClientId}&redirect_uri=oauth2-swift://oauth-callback/eventbrite&response_type=code
我已将“oauth-swift”URL 方案添加到 info.plist。
这是我的 eventbrite 应用程序设置: 申请网址:http://mywebsite.com OAuth 重定向 Uri:oauth-swift://oauth-callback/eventbrite
如何将用户重定向到我的应用程序以便检索访问 token ?当我尝试验证 Eventbrite 时,不会调用应用程序委托(delegate)/openURL 函数(当我尝试使用 Foursquare 和 Instagram 时,它会被调用)。另外,我尝试了使用 Foursquare 和 Instagram 进行 OAuth2,效果很好。
我是否缺少 OAuth2 w eventbrite 的应用程序设置、代码等特定内容?谢谢
最佳答案
在 iOS 中使用 OAuth 时需要注意的几点:
- 如果您计划在 App Store 中分发您的应用,请确保不使用 Safari 进行身份验证。您必须在应用程序中执行此操作,最好的地方是使用 WebView。
- 切勿将您的应用/消费者 secret 存储在您的 iOS 应用中。
现在,如何通过WebView实现OAuth认证?
- 如果您使用 Storyboard,请将 WebView 拖到 ViewController 中。还要为 ViewController 创建一个类文件,并为 WebView 创建一个 IBOutlet。
在 ViewController 的
viewDidAppear
函数中设置 WebView 来加载您的授权 URL。authorisationURL = "https://www.eventbrite.com/oauth/authorize?client_id=YOUR_CLIENT_KEY&response_type=code&redirect_uri=REDIRECT_URI" self.webView.loadRequest(NSURLRequest(URL: NSURL(string: authorisationURL)!))
- 将
UIWebViewDelegate
协议(protocol)添加到 ViewController 并添加函数webViewDidFinishLoad(webView: UIWebView)
。只要 WebView 完成加载页面,就会调用此函数。 一旦用户提供对您的应用程序的访问权限,Eventbrite 会将您重定向到您随代码提供的重定向 uri。例如
https://localhost?code=xxxx
。我们可以通过读取此 URL 来访问代码。if (webView.request?.URL?.absoluteString!.rangeOfString("code=") != nil) { let queryString = webView.request?.URL?.query println(queryString) let authenticationCode = queryString!.substringFromIndex(advance(codeContainer!.startIndex, 5)) // we are advancing 5 characters in order to ignore "code=" }
现在您已获得代码,是时候使用您的后端检索访问 token 了。您可以访问网络服务器吗?如果是,你只需要将上面获取到的代码传递给你的后台,并从你的后台发起POST请求即可。 Eventbrite 将使用访问 token 响应您,您可以将其存储在后端(推荐)或客户端中。
method: 'POST',
url: 'https://www.eventbrite.com/oauth/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
'client_id' : '*******',
'client_secret' : '********',
'grant_type' : 'authorization_code',
'code' : CODE_RECEIVED_FROM_ABOVE
}
如果您无法访问网络服务器,您可以尝试 Parse.com。
关于ios - 使用 iOS/swift 对 OAuth2 和 Eventbrite 进行身份验证时出现 “Oops, something went wrong” 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32148257/