我正在努力获取 Quizlet (oauth2) 上的访问令牌。到目前为止一切正常,我可以让用户在 Quizlet 上接受我的应用程序,得到重定向,但是当通过 NSURLConnection 请求访问令牌时,我总是收到以下错误:
2013-08-17 09:39:33.422 Abiliator[49549:c07] 以字符串格式返回数据:{"http_code":400,"error":"invalid_request","error_title":"Not Allowed","error_description": “无效的 grant_type 参数或缺少参数”}
这里是用户身份验证的代码(根据规范必须通过浏览器):
- (void) authenticateQuizletUser
{
NSString *quizletRandomString = [abiliatorAppDelegate GetUUID];
NSString *authURLString = [@"https://quizlet.com/authorize/?response_type=code&client_id=" stringByAppendingString:@"<myID>&scope=read"];
authURLString = [authURLString stringByAppendingString:@"&state="];
authURLString = [authURLString stringByAppendingString:quizletRandomString];
authURLString = [authURLString stringByAppendingString:@"&redirect_uri=Abiliator://after_oauth"];
NSLog(@"Authentication URL sent: %@", authURLString);
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: authURLString]];
}
正如我所提到的,这很好用。该应用程序启动 Safari,用户必须确认输入用户 ID 和密码的请求,服务器重定向到我的应用程序,我在下面的方法中捕获它,然后抛出描述的错误。
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
if (!url) { return NO; }
NSString *URLString = [url absoluteString];
NSLog(@"Received URL: %@", URLString);
NSString *myURLQuery = [url query];
NSString *myAuthCode = [self getAuthorizationCodeFromURL:myURLQuery];
NSLog(@"Component1: %@", myAuthCode);
NSString *authPasswd = @"myPasswd";
NSString *username=@"myUserName";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.quizlet.com/oauth/token"]];
request.HTTPMethod = @"POST";
[request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"Abiliator://after_oauth" forHTTPHeaderField:@"redirect_uri"];
// According to Quizlet API doc: You must set this (grant_type) to the string "authorization_code".
[request setValue:@"authorization_code" forHTTPHeaderField:@"grant_type"];
[request setValue:myAuthCode forHTTPHeaderField:@"code"];
NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, authPasswd];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
return YES; }
任何帮助都非常感谢。