ios - Uber 身份验证失败 "HTTP Status 401: Unauthorized, Response: {"错误“: "invalid_client"}"

标签 ios iphone swift authentication uber-api

我正在使用 this Uber 身份验证库

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

我这样做过

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

}

但得到这个回应 HTTP 状态 401:未经授权,响应:{"error": "invalid_client"}

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

更新:1

这是有线的,我将 responseType: "code"更改为 responseType: "token"并且它工作得到了我的访问 token 。但我现在遇到了另一个问题

现在每当我尝试调用 request endpoint api

使用下面的代码

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


}

我收到了这个回复

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

最佳答案

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

见下图。

enter image description here

所以最终我不得不从授权代码中删除 #_,然后再使用它来获取访问 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];
}];

希望这对您或遇到类似问题的任何人有所帮助。

关于ios - Uber 身份验证失败 "HTTP Status 401: Unauthorized, Response: {"错误“: "invalid_client"}",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30073051/

相关文章:

ios - 带有 CGAffineTransform 的 View 的 UIDynamicAnimator

ios - amazon s3 iphone sdk 下载图片

iphone - 您可以更改在 iOS 的 safari 中更改方向时显示的内容吗?

swift - iOS 9 基本 HTTP 请求

ios - 我想在与 api 数据对应的标签中将可用时间显示为粗体和不可用时间(罢工)

ios - iOS 7 应用程序如何使自己透明以查看用户的主屏幕图像?

ios - layer被constraints更新后调用@IBDesignable中的@IBInspectable set

iphone - MPMoviePlayerController 自定义控件

ios - UIImageView 的深层复制没有复制 iOS 中应用于原始 View 的所有委托(delegate)和手势

ios - 如何从该 segue 或目标 View Controller 访问执行 segue 的源 View ?