1

i am using this library for Uber Authetication

https://developer.uber.com/v1/auth/

I have done like this

func doOAuthUber(){

let oauthswift = OAuth2Swift(
    consumerKey:    "fXfXXXXXXXUo9vtKzobXXXXXUDO",
    consumerSecret: "e5XXXXXXXq2w63qz9szEx7uXXXXXXo03W",
    authorizeUrl:   "https://login.uber.com/oauth/authorize",
    accessTokenUrl: "https://login.uber.com/oauth/token",
    responseType:   "code"
)

var originalString = "jamesappv2://oauth/callback"
var encodedCallBackUrl = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

println("encodedCallBackUrl: \(encodedCallBackUrl)")


let state: String = ""
oauthswift.authorizeWithCallbackURL( NSURL(string: encodedCallBackUrl!)!, scope: "request%20history", state: state, success: {
    credential, response in

    println(credential.oauth_token)
    self.personalDriverLoader.stopAnimating()



    }, failure: {(error:NSError!) -> Void in

        self.personalDriverLoader.stopAnimating()
        println(error.localizedDescription)
})

}

but getting this response HTTP Status 401: Unauthorized, Response: {"error": "invalid_client"}

I have triple checked that my client_id (consumerKey) and secret (consumerSecret) are correct. What I have done wrong here

Update:1

this is wired I changed responseType: "code" to responseType: "token" and it worked Got My access token. but I am getting an other issue now

now when ever I try to call the request endpoint api

using below code

@IBAction func btnRequestUberdidClicked(sender: AnyObject) {

    self.callRequestAPI("https://sandbox-api.uber.com/v1/requests")

}

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]



    appDelegate.oauthswift.client.post(url, parameters: params,
    success: { data, response in

    let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)


         println("Success")

                    println(data)

                    println(response)


        }, failure: {(error:NSError!) -> Void in

                         println("Error")

                    println(error)
    })


}

I am getting this response

Error Domain=NSURLErrorDomain Code=401 "HTTP Status 401: Unauthorized, Response: {"message":"Invalid OAuth 2.0 credentials provided.","code":"unauthorized"}" UserInfo=0x1c563220 {NSLocalizedDescription=HTTP Status 401: Unauthorized, Response: {"message":"Invalid OAuth 2.0 credentials provided.","code":"unauthorized"}, Response-Headers=<CFBasicHash 0x1c578c40 [0x35305710]>{type = immutable dict, count = 7,
entries =>
    1 : x-xss-protection = <CFString 0x1ae2fc60 [0x35305710]>{contents = "1; mode=block"}
    4 : Server = <CFString 0x1acc24c0 [0x35305710]>{contents = "nginx"}
    5 : Content-Type = <CFString 0x1c4d0020 [0x35305710]>{contents = "application/json"}
    6 : Content-Length = <CFString 0x1c4b70b0 [0x35305710]>{contents = "75"}
    8 : Date = <CFString 0x1c4ed4b0 [0x35305710]>{contents = "Wed, 06 May 2015 12:46:51 GMT"}
    10 : Strict-Transport-Security = <CFString 0x1c225cb0 [0x35305710]>{contents = "max-age=31536000; includeSubDomains; preload"}
    11 : x-uber-app = <CFString 0x1c49a6b0 [0x35305710]>{contents = "uberex-sandbox"}
}
}
Qadir Hussain
  • 8,721
  • 13
  • 89
  • 124
  • Uber API needs OAuth2 but you're using OAuth1's format of your lib. Check https://github.com/dongri/OAuthSwift#examples . And look in the [Uber API doc](https://developer.uber.com/v1/auth/), the auth is done in *three* steps, not one. :) – Eric Aya May 06 '15 at 10:18
  • @EricD. thanks for response. how to use Oauth2 using this library. let me know what is wrong with this. you can see i have used OAuth2Swift – Qadir Hussain May 06 '15 at 12:26
  • You're using the right `OAuth2Swift` object, *but* in it you're using the wrong declaration format. Look at the *last* example on the OAuthSwift page, there shouldn't be any `accessTokenUrl` in it. The, once you've got this response, follow the *redirect*, then, eventually, get the token. :) – Eric Aya May 06 '15 at 12:35
  • this is wired I changed responseType: "code" to responseType: "token" and it worked (o0) . Got My access token. but I am getting an other issue now – Qadir Hussain May 06 '15 at 12:40
  • I don't have an Uber account anymore, so I can't test or help any further with your example. Anyway, while searching for informations, I found your [previous question](http://stackoverflow.com/a/29918588/2227743) where you seemed to have found a way to achieve this!!! I'm a bit puzzled now. :p – Eric Aya May 06 '15 at 13:23
  • This is wrong, an access token url is most certainly required. It will crash if it's not included because it tries to use that to get a token later in OAuthSwiftHTTPRequest. – Nathan McKaskle Aug 23 '15 at 20:19
  • I'm also having this same problem. It's inexplicable at this point. I thought I had fixed it one time when I was missing a privacy policy and hadn't selected the scope correctly on their page, but now the problem is back and makes no sense at all. – Nathan McKaskle Aug 23 '15 at 20:35

2 Answers2

0

You will have to modify the library where possible and be able to print the auth code returned from Uber. I was facing a similar problem with Uber authentication using objective C and then I realised from my logs that Uber was appending #_ to the authorization code. So when this code was used to fetch the access token, it would fail with (401) unauthorised error simply saying the auth code is invalid, and indeed it was.

See attached image below.

enter image description here

So eventually I had to removed the #_ from the auth code before using it to get the access token.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params1 = @{@"client_secret":UBER_CLIENT_SECRET,
                          @"client_id":UBER_CLIENT_ID,
                          @"grant_type":@"authorization_code",
                          @"redirect_uri":UBER_REDIRECT_URL,
                          @"code":[app.uberAuthCodeStr stringByReplacingOccurrencesOfString:@"#_" withString:@""]};
                    //******* THE FIX IS HERE ON THIS LINE ^^^

[manager POST:@"https://login.uber.com/oauth/v2/token" parameters:params1 success:^(AFHTTPRequestOperation *operation, id responseObject){
    NSLog(@"JSON: %@", responseObject);
    //
    app.uberBearerAccess_token = [responseObject valueForKey:@"access_token"];
    app.uberBearerRefresh_token = [responseObject valueForKey:@"refresh_token"];
    NSLog(@"Bearer AccessToken = %@ ",app.uberBearerAccess_token);
    // Save access token to user defaults for later use.
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSNumber *seconds = [responseObject objectForKey:@"expires_in"];
    NSDate *expiryDate = [[NSDate date] dateByAddingTimeInterval:seconds.intValue];
    [defaults setObject:expiryDate forKey:KEY_UBER_TOKEN_EXPIRE_DATE];
    [defaults setObject:app.uberBearerAccess_token forKey: KEY_UBER_TOKEN];
    [defaults setObject:app.uberBearerRefresh_token forKey: KEY_UBER_REFRESH_TOKEN];
     [defaults setObject:app.uberAuthCodeStr forKey: KEY_UBER_AUTH_CODE];
    [defaults synchronize];
    loginView.hidden = YES;
    [self goUberChat];
    //
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@':%@", error,params1);
    [ProgressHUD dismiss];
}];

Hope this helps you or anyone with a similar problem.

nmvictor
  • 1,109
  • 1
  • 15
  • 30
-3

Try this for call Uber Api

 NSString *string=[NSString stringWithFormat:@"https://api.uber.com/v1/products"];
    NSURL *url=[NSURL URLWithString:string];
    AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc]initWithBaseURL:url];
    NSDictionary *parameters = @{@"server_token":@"Your token",@"latitude":@"latitude",@"longitude":@"longitude",
    [manager GET: parameters:parameters progress:nil success:^(NSURLSessionTask *task,id responseObject){
    } failure:^(NSURLSessionTask *operation , NSError *error)
}];
CodeMouse92
  • 6,840
  • 14
  • 73
  • 130
DURGESH
  • 2,373
  • 1
  • 15
  • 13
  • While this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – CodeMouse92 May 03 '16 at 18:35