【发布时间】:2015-02-01 02:48:53
【问题描述】:
我正在尝试使用原生 iOS NSURLSession URL 加载类创建一个使用 OAuth2 身份验证的 iOS 应用。我使用此处的说明获得了访问令牌:
我随后启动应用程序并运行搜索查询
https://www.freesound.org/apiv2/search/text/?query=snare
请求标头字段如下所示(注意我的访问令牌未过期,我已确认它与执行上述步骤时收到的相同)
{
"Authorization: Bearer" = MY_ACCESS_TOKEN;
}
这失败了:
{"detail": "Authentication credentials were not provided."}
响应标头如下所示:
{
Allow = "GET, HEAD, OPTIONS";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Sat, 31 Jan 2015 13:56:32 GMT";
Server = "nginx/1.2.1";
"Transfer-Encoding" = Identity;
Vary = "Accept, Cookie";
"Www-Authenticate" = "Bearer realm=\"api\"";
}
有趣的是,这并不总是发生。如果我多次重复整个过程,删除中间的应用程序,它最终会起作用。一旦它工作,它将在我开发时继续工作。有时当我回到它时,比如说第二天,它停止工作,我需要重复这个删除和重新安装程序才能让它再次工作!
在 NSURLSession 上有一个身份验证质询委托方法,如果实现,它将被调用。这是一个“服务器信任”挑战。这可能与它有关吗?您甚至会期待这种性质的身份验证挑战吗?上面提到的文档中没有提到它。
任何帮助将不胜感激。
编辑
这就是搜索文本(“snare”)GET 调用的方式。
我基本上传入了一个NSMutableURLRequest,并将 URL 设置为上述 (https://www.freesound.org/apiv2/search/text/?query=snare)。 useAccessToken 设置为 YES。
- (void)makeRequest:(NSMutableURLRequest *)request useAccessToken:(BOOL)useAccessToken completion:(CompletionBlock)completion {
NSAssert(completion, @"No completion block.");
if (useAccessToken) {
NSString *accessToken = [[ODMFreesoundTokenCache sharedCache] accessToken];
NSAssert(accessToken.length, @"No access token.");
[request addValue:accessToken forHTTPHeaderField:@"Authorization: Bearer"];
}
NSLog(@"Making request: %@ \n\nWith access token: %@", request, [[ODMFreesoundTokenCache sharedCache] accessToken]);
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSInteger code = [(NSHTTPURLResponse *)response statusCode];
if (code == 200) {
if (!error) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"json: %@", json);
completion(json, error);
}
else {
completion(nil, error);
}
}
else {
NSString *reason = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *error = [NSError errorWithDomain:@"Request Error" code:code userInfo: reason ? @{NSLocalizedDescriptionKey : reason} : nil];
NSLog(@"error: %@", error);
completion(nil, error);
}
}];
[task resume];
}
【问题讨论】:
标签: ios authentication oauth-2.0 nsurlsession