草庐IT

ios - 带有 OAuth2 token 的 AFNetworking 2.0

coder 2023-09-29 原文

我正在尝试找到一种将 OAuth2(访问和刷新 token )与 AFNetworking 一起使用的方法。我很难找到关于它的好文档。

我知道 AFOAuth2Client 项目,但它只适用于 AFNetworking 1.xAFNetworking 2.0有什么好的解决方案吗?

此外, token 将如何刷新?我是否应该始终检查每个请求的 token 是否过期?究竟在哪里可以做到这一点?或者在 token 过期时使用计时器,然后获取一个新计时器?

最佳答案

为了解决您关于 token 刷新的问题,下面是我在最近几个项目中使用的代码,用于在每次请求时根据需要检查和刷新 token 。

基本上,它只是将请求 block 传递给一个方法来进行 token 检查,然后在 token 良好或刷新 token 后立即运行该 block 。

- (void)refreshAccessTokenWithSuccess:(APIClientSuccess)success
                              failure:(APIClientFailure)failure {
    if (self.credential == nil) {
        if (failure) {
            // Failed to get credentials
        }
        return;
    }
    if (!self.credential.isExpired) {
        if (success) {
            success(nil, nil);
        }
        return;
    }
    [self authenticateUsingOAuthWithURLString:kOAuthURL
                            refreshToken:self.credential.refreshToken
                                 success:^(AFOAuthCredential *newCredential) {
                                     // SUCCESS!
                                     self.credential = newCredential;
                                     if (success) {
                                         success(nil, nil);
                                     }
                                 }
                                 failure:^(NSError *error) {
                                     // Failed to get credentials
                                     if (failure) {
                                         failure(nil, error);
                                     }
                                 }];
}
- (void)RefreshGET:(NSString *)URLString
 parameters:(NSDictionary *)parameters
    success:(APIClientSuccess)success
    failure:(APIClientFailure)failure
{
    APIClientSuccess nestedSuccess  = ^(AFHTTPRequestOperation *operation, id responseObject) {
        AFHTTPRequestOperation *thisRequestOperation = [super GET:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (success) {
                success((AFHTTPRequestOperation *)operation, responseObject);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // Failed request
            if (failure) {
                failure((AFHTTPRequestOperation *)operation, error);
            }
        }];
    };
    [self refreshAccessTokenWithSuccess:nestedSuccess failure:failure];
}

如果您想查看整个 APIClient 类,请告诉我。

关于ios - 带有 OAuth2 token 的 AFNetworking 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106498/

有关ios - 带有 OAuth2 token 的 AFNetworking 2.0的更多相关文章

  1. ruby-on-rails - Rails 中的 NoMethodError::MailersController#preview undefined method `activation_token=' for nil:NilClass - 2

    似乎无法为此找到有效的答案。我正在阅读Rails教程的第10章第10.1.2节,但似乎无法使邮件程序预览正常工作。我发现处理错误的所有答案都与教程的不同部分相关,我假设我犯的错误正盯着我的脸。我已经完成并将教程中的代码复制/粘贴到相关文件中,但到目前为止,我还看不出我输入的内容与教程中的内容有什么区别。到目前为止,建议是在函数定义中添加或删除参数user,但这并没有解决问题。触发错误的url是http://localhost:3000/rails/mailers/user_mailer/account_activation.http://localhost:3000/rails/mai

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  4. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. ruby-on-rails - 带有 Zeus 的 RSpec 3.1,我应该在 spec_helper 中要求 'rspec/rails' 吗? - 2

    使用rspec-rails3.0+,测试设置分为spec_helper和rails_helper我注意到生成的spec_helper不需要'rspec/rails'。这会导致zeus崩溃:spec_helper.rb:5:in`':undefinedmethod`configure'forRSpec:Module(NoMethodError)对thisissue最常见的回应是需要'rspec/rails'。但这是否会破坏仅使用spec_helper拆分rails规范和PORO规范的全部目的?或者这无关紧要,因为Zeus无论如何都会预加载Rails?我应该在我的spec_helper中做

  7. Ruby:如何使用带有散列的 'send' 方法调用方法? - 2

    假设我有一个类A,里面有一些方法。假设stringmethodName是这些方法之一,我已经知道我想给它什么参数。它们在散列中{'param1'=>value1,'param2'=>value2}所以我有:params={'param1'=>value1,'param2'=>value2}a=A.new()a.send(methodName,value1,value2)#callmethodnamewithbothparams我希望能够通过传递我的哈希以某种方式调用该方法。这可能吗? 最佳答案 确保methodName是一个符号,而

  8. ruby-on-rails - 使用 HTTP.get_response 检索 Facebook 访问 token 时出现 Rails EOF 错误 - 2

    我试图在我的网站上实现使用Facebook登录功能,但在尝试从Facebook取回访问token时遇到障碍。这是我的代码:ifparams[:error_reason]=="user_denied"thenflash[:error]="TologinwithFacebook,youmustclick'Allow'toletthesiteaccessyourinformation"redirect_to:loginelsifparams[:code]thentoken_uri=URI.parse("https://graph.facebook.com/oauth/access_token

  9. ruby-on-rails - 带有 Pry 的 Rails 控制台 - 2

    当我进入Rails控制台时,我已将pry设置为加载代替irb。我找不到该页面或不记得如何将其恢复为默认行为,因为它似乎干扰了我的Rubymine调试器。有什么建议吗? 最佳答案 我刚发现问题,pry-railsgem。忘记了它的目的是让“railsconsole”打开pry。 关于ruby-on-rails-带有Pry的Rails控制台,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/question

  10. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

随机推荐