在 ios 中使用 NSURLSessions 对服务器 API 进行 oAuth2 身份验证

oAuth2 authentication of server API using NSURLSessions in ios

如果您发现此问题与完整上下文相似或不清楚,请耐心等待,发布我的第一个问题,所以我会在习惯后改进。 我试图搜索类似的问题陈述以找到接近的解决方案。

我有我的网络服务器提供的客户端 ID、密码、重定向 URL,以便它可以使用 oauth2 身份验证来验证其 API 的使用。因此,在使用其任何 Web 服务之前,一开始客户端必须进行授权令牌握手以接收要提供给 API 调用的令牌。

在我的 IOS 客户端应用程序中创建一个 NSURL 像这样:

NSString* urlString = [NSString stringWithFormat:@"%@/oauth/authorize/?client_id=%@&response_type=code&redirect_uri=%@",myServerHostName, myAppClientId,myServerRedirectHostname];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"utf-8"  forHTTPHeaderField:@"charset"];
[request setHTTPMethod:@"POST"];

正在创建一个 NSURLSession 和 NSURLSessionDataTask 以及带有上述 NSURLRequest:

的适当参数
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request];
[postDataTask resume];

并创建了一个委托重定向处理程序,因此我可以获取新的重定向 URL,例如:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionDataTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)newRequest completionHandler:(void (^)(NSURLRequest *))completionHandler {

      //Doing stuff : Grab the new redirected URL to get the oauth2 code. from the URL.
}

这是在他们的 access/usage 之前执行用于验证 API 的 oauth2 的合法方式吗?

目前我的服务器在收到上述请求时失败并抛出 500。

Completed 500 Internal Server Error in 14ms

NameError (undefined local variable or method `login_path' for #<Doorkeeper::AuthorizationsController:0x000001078c1560>)

但是当我通过网络尝试此操作时:使用 'Advanced REST client' 的示例,客户端成功接收到重定向 URL(状态代码 302)。

后来发现发送请求是完全正确的,服务器端使用的是门卫 gem 实现,实习生重定向到注册 link 进行身份验证,因为重定向是失败因此收到错误 500。没有理想的用户帐户,任何 API 的 oauth2 身份验证都无法完成。