优步身份验证失败“HTTP状态401:未经授权,响应:{”错误“:”invalid_client“}”

时间:2022-08-09 08:17:23

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

但得到此响应HTTP状态401:未经授权,响应:{“error”:“invalid_client”}

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

我已经三次检查我的client_id(consumerKey)和secret(consumerSecret)是否正确。我在这里做错了什么

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

这是有线的我改变了responseType:“code”到responseType:“token”,它工作了Get My access token。但我现在正在接受另一个问题

now when ever I try to call the request endpoint api

现在,当我尝试调用请求端点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"}
}
}

2 个解决方案

#1


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.

您必须尽可能修改库,并能够打印从优步返回的身份验证代码。我在使用目标C进行Uber身份验证时遇到了类似的问题,然后我从我的日志中意识到Uber正在将#_附加到授权代码中。因此,当使用此代码获取访问令牌时,它会因(401)未授权的错误而失败,只是说auth代码无效,事实确实如此。

See attached image below.

见下图。

优步身份验证失败“HTTP状态401:未经授权,响应:{”错误“:”invalid_client“}”

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

所以最终我必须从auth代码中删除#_才能使用它来获取访问令牌。

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.

希望这可以帮助您或任何有类似问题的人。

#2


Try this for call Uber Api

试试这个叫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)
}];

#1


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.

您必须尽可能修改库,并能够打印从优步返回的身份验证代码。我在使用目标C进行Uber身份验证时遇到了类似的问题,然后我从我的日志中意识到Uber正在将#_附加到授权代码中。因此,当使用此代码获取访问令牌时,它会因(401)未授权的错误而失败,只是说auth代码无效,事实确实如此。

See attached image below.

见下图。

优步身份验证失败“HTTP状态401:未经授权,响应:{”错误“:”invalid_client“}”

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

所以最终我必须从auth代码中删除#_才能使用它来获取访问令牌。

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.

希望这可以帮助您或任何有类似问题的人。

#2


Try this for call Uber Api

试试这个叫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)
}];