gpt4 book ai didi

ios - Uber 在 ios Swift 中提供了无效的 OAuth 2.0 凭据 Uber 身份验证

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:49 27 4
gpt4 key购买 nike

我正在实现 Uber's Request Endpoint在我的 iOS (Swift) 应用程序中。请求 API/端点需要应用程序的用户身份验证,这里是 doc .

为此,我使用了这个 Oauth2.0 library

我做的是

  1. 在给定的安装说明的帮助下,成功地将库集成到我的项目 (xCode) 中。

  2. 在我的 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!

  3. 在我的 Appdelegate 方法 didFinishLaunchingWithOptions

     oauth = OAuth2CodeGrant(settings: uber_OAuth_Settings)
    oauth.viewTitle = "Uber Login Service" // optional
    oauth.verbose = true // For Logs
  4. 不要忘记注册 url 方案,即 ("redirect_uris": ["jamesappv2://oauth/callback"])

转到您应用的目标 -> 信息选项卡 -> 网址类型 -> 单击 (+),附上图片

enter image description here

  1. 在 AppDelegate 中添加下面给出的方法并处理回调 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
    }
  2. 现在在我的 viewController 中,我在 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)")
    }
    }

这是我的调试日志,我得到了有效的响应:

    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]

注意我正在获取有效的 access_token

我卡在这里了

根据 DOCs在 STEP4 *USE BEARER TOKEN 中说

将 Authorization header 中响应中返回的 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){

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()
}

但我得到了以下回应

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"})

最佳答案

我终于做到了:)

我改变了下面的方法,它起作用了

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()

}

这是我得到的响应,我上面的方法也给出了解析

{
driver = "<null>";
eta = 15;
location = "<null>";
"request_id" = "ea39493d-b718-429f-8710-00a34dcdaa93";
status = processing;
"surge_multiplier" = 1;
vehicle = "<null>";
}

享受

关于ios - Uber 在 ios Swift 中提供了无效的 OAuth 2.0 凭据 Uber 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29895238/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com