优步无效的 OAuth 2.0 凭据在 ios Swift 中提供优步身份验证 [英] Uber Invalid OAuth 2.0 credentials provided Uber Authentication In ios Swift
问题描述
我正在我的 iOS (Swift) 中实施 在 STEP4 中说 *USE BEARER TOKEN
在 Authorization 标头中传递响应中返回的 access_token 类型为 Bearer 以代表用户发出请求.*
curl -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' 'https://api.uber.com/v1/products?latitude=37.7759792&longitude=-122.41823'
我没听明白.我应该如何在类型为 Bearer 的 Header 中传递 access_token?我做了如下
func callRequestAPI(url:String){让 request = appDelegate.oauth.request(forURL: NSURL(string:url)!)request.HTTPMethod = "POST"let postString = "product_id="+selectedUberProductId+"&start_latitude="+start_lat+"&start_longitude="+start_lng+"&end_latitude="+end_lat+"&end_longitude="+end_lng打印(后字符串)让 tempData: NSData = appDelegate.oauth.accessToken.dataUsingEncoding(NSUTF8StringEncoding)!让 base64LoginString = tempData.base64EncodedStringWithOptions(nil)request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)request.addValue("application/json", forHTTPHeaderField: "Content-Type")request.addValue("application/json", forHTTPHeaderField: "Accept")request.setValue("Bearer (base64LoginString)", forHTTPHeaderField: "Authorization")让会话 = NSURLSession.sharedSession()让任务 = session.dataTaskWithRequest(request) { 数据,响应,错误如果错误 != nil {println("错误=(错误)")返回}println("响应 = (响应)")让 responseString = NSString(data: data, encoding: NSUTF8StringEncoding)println("responseString = (responseString)")}任务.resume()}
但我收到以下回复
response = { URL: https://sandbox-api.uber.com/v1/requests } { 状态码:401, headers {内容长度"= 75;内容类型"=应用程序/json";日期 = "2015 年 4 月 27 日星期一 10:22:01 GMT";服务器 = nginx;"Strict-Transport-Security" = "max-age=31536000; includeSubDomains; preload";"x-uber-app" = "uberex-sandbox";x-xss-protection"=1;模式=块";} }responseString = Optional({"message":"提供的 OAuth 2.0 凭据无效.","code":"unauthorized"})
我终于搞定了 :)
我改变了下面的方法,它奏效了
func callRequestAPI(url:String){var 配置 = NSURLSessionConfiguration.defaultSessionConfiguration()var session = NSURLSession(配置:配置)让参数:[字符串:AnyObject] = [product_id":选定的UberProductId,开始纬度":开始纬度,"start_longitude" : start_lng,"end_latitude" : end_lat,end_longitude":end_lng]让 request = appDelegate.oauth.request(forURL: NSURL(string:url)!)request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")request.HTTPMethod = "POST"变量错误:NSError?request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)让任务 = session.dataTaskWithRequest(request) {数据,响应,错误如果让 httpResponse = response as?NSHTTPURLResponse {如果 httpResponse.statusCode != 202 {println("响应不是 202:(响应)")返回}}如果(错误!= nil){println("提交请求出错:(error)")返回}//这里处理成功响应的数据var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as!NSD字典打印(结果)if let request_id: String = result["request_id"] as?细绳{println(request_id)}if let driver: String = result["driver"] as?细绳{打印(驱动程序)}if let eta: Int = result["eta"] as?整数{打印(eta)}if let location: String = result["location"] as?细绳{打印(位置)}if let status: String = result["status"] as?细绳{打印(状态)}if let Surge_multiplier: Int = result["surge_multiplier"] as?整数{println(surge_multiplier)}如果让车辆:String = result["vehicle"] as?细绳{println(车辆)}}任务.resume()}
这是我得到的响应,解析也在我上面的方法中给出
<代码>{驱动程序 = "";eta = 15;location = " ";"request_id" = "ea39493d-b718-429f-8710-00a34dcdaa93";状态 = 处理中;surge_multiplier"= 1;车辆 = " ";}
享受
I'm implementing the Uber's Request Endpoint in my iOS (Swift) App. The Request API/Endpoint requires the user authentication with the app, here is the doc.
For this I'm using this Oauth2.0 library
What I did is
successfully integrated the Library in my project (xCode) with the help of given installation instructions.
In My AppDelegate
let uber_OAuth_Settings = [ "client_id": "XXXXXXX9vtKzobvXXXXXX", "client_secret": "EXXXXXXXXyFUNCa_Wez6AXXXXXXXnrXtxus", "authorize_uri": "https://login.uber.com/oauth/authorize", "token_uri": "https://login.uber.com/oauth/token", "redirect_uris": ["jamesappv2://oauth/callback"], // don't forget to register this scheme ] as OAuth2JSON
var oauth:OAuth2CodeGrant!
in my method
didFinishLaunchingWithOptions
of Appdelegateoauth = OAuth2CodeGrant(settings: uber_OAuth_Settings) oauth.viewTitle = "Uber Login Service" // optional oauth.verbose = true // For Logs
Don't forget to register url scheme i.e (
"redirect_uris": ["jamesappv2://oauth/callback"]
)
goto your app's Target -> info Tab -> Url Types -> Click (+), image attached
In AppDelegate add method given Below and Handle the Callback Url
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { // you should probably first check if this is your URL being opened var splitUrl = url.absoluteString!.componentsSeparatedByString(":") if splitUrl[0] == ("jamesappv2") { oauth.handleRedirectURL(url) } return true }
Now in my viewController I did like this on myBtnClick
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let url = appDelegate.oauth.authorizeURL() UIApplication.sharedApplication().openURL(url) appDelegate.oauth.onAuthorize = { parameters in println("Did authorize with parameters: (parameters)") self.navigationController?.pushViewController(self.PersonalDriverUber_VC, animated: true) //On Authorization Goto another ViewController using pushViewController of navigationcontroller Method } appDelegate.oauth.onFailure = { error in // `error` is nil on cancel if nil != error { println("Authorization went wrong: (error!.localizedDescription)") } }
Here is my debug log, I'm getting the valid response:
OAuth2: Handling redirect URL jamesappv2://oauth/callback?state=4B0EB812&code=0sXXXXXXTX7yEbS1XXXXXHuw
OAuth2: Successfully validated redirect URL
OAuth2: Authorizing against https://login.uber.com/oauth/token?state=38158941&grant_type=authorization_code&code=0sXXXXXXXX1jxTrdFQT9Huw&client_secret=EIXXXXXXXNCa_Wez6XXXXXw0BlnrXtxus&client_id=fXXXXXXXy2LOUo9vtKXXXXXQ1nUDO&redirect_uri=jamesappv2%3A%2F%2Foauth%2Fcallback
OAuth2: Exchanging code 0swNXXXXX7yXXXXXXdFQT9Huw with redirect jamesappv2://oauth/callback for token at Optional("https://login.uber.com/oauth/token")
OAuth2: Did receive access token: Dfq3XXXXXXuWgpaqFXXXXXXXgXW, refresh token: EmStT7FEXHRMlS8odPzs1nsha0ObjK
Did authorize with parameters: [token_type: Bearer, expires_in: 2592000, access_token: XXXXXXOZuWgXXXXXXXXuJYOmgXW, refresh_token: EXXXXXHRMlS8oXXXXXXXa0ObjK, scope: profile, last_authenticated: 1430121470]
Notice I'm getting the valid access_token
Here I'm stuck
As per DOCs says in STEP4 *USE BEARER TOKEN
Pass the access_token returned in the response in the Authorization header with the type Bearer to make requests on behalf of a user.*
curl -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' 'https://api.uber.com/v1/products?latitude=37.7759792&longitude=-122.41823'
I am not getting the point. How should I pass the access_token in Header with type Bearer? I have done like below
func callRequestAPI(url:String){
let request = appDelegate.oauth.request(forURL: NSURL(string:url)!)
request.HTTPMethod = "POST"
let postString = "product_id="+selectedUberProductId+"&start_latitude="+start_lat+"&start_longitude="+start_lng+"&end_latitude="+end_lat+"&end_longitude="+end_lng
println(postString)
let tempData: NSData = appDelegate.oauth.accessToken.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = tempData.base64EncodedStringWithOptions(nil)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("Bearer (base64LoginString)", forHTTPHeaderField: "Authorization")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
if error != nil {
println("error=(error)")
return
}
println("response = (response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = (responseString)")
}
task.resume()
}
but I'm getting following response
response = <NSHTTPURLResponse: 0x1a284b50> { URL: https://sandbox-api.uber.com/v1/requests } { status code: 401, headers {
"Content-Length" = 75;
"Content-Type" = "application/json";
Date = "Mon, 27 Apr 2015 10:22:01 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=31536000; includeSubDomains; preload";
"x-uber-app" = "uberex-sandbox";
"x-xss-protection" = "1; mode=block";
} }
responseString = Optional({"message":"Invalid OAuth 2.0 credentials provided.","code":"unauthorized"})
Finally I have done it :)
I changed the method like below and it Worked
func callRequestAPI(url:String){
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
let params:[String: AnyObject] = [
"product_id" : selectedUberProductId,
"start_latitude" : start_lat,
"start_longitude" : start_lng,
"end_latitude" : end_lat,
"end_longitude" : end_lng]
let request = appDelegate.oauth.request(forURL: NSURL(string:url)!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)
let task = session.dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 202 {
println("response was not 202: (response)")
return
}
}
if (error != nil) {
println("error submitting request: (error)")
return
}
// handle the data of the successful response here
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as! NSDictionary
println(result)
if let request_id: String = result["request_id"] as? String{
println(request_id)
}
if let driver: String = result["driver"] as? String{
println(driver)
}
if let eta: Int = result["eta"] as? Int{
println(eta)
}
if let location: String = result["location"] as? String{
println(location)
}
if let status: String = result["status"] as? String{
println(status)
}
if let surge_multiplier: Int = result["surge_multiplier"] as? Int{
println(surge_multiplier)
}
if let vehicle: String = result["vehicle"] as? String{
println(vehicle)
}
}
task.resume()
}
here is the Response I Got, Parsing is also given in my above method
{
driver = "<null>";
eta = 15;
location = "<null>";
"request_id" = "ea39493d-b718-429f-8710-00a34dcdaa93";
status = processing;
"surge_multiplier" = 1;
vehicle = "<null>";
}
Enjoy
这篇关于优步无效的 OAuth 2.0 凭据在 ios Swift 中提供优步身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!