ios - 如何在 NXOAuth2 中使用保存的 token ?

标签 ios objective-c oauth-2.0 oauth2client

我正在尝试使用 NXOauth2 pod 在我的 iOS 应用程序上处理 OAuth2 来实现解决方案。

我能够通过已安装的应用程序流程获取 OAuth2 属性,包括 accessTokenrefreshToken - 并且该帐户正在保存到我的 NXOAuth2AccountStore 正确(通过检查 [[NXOAuth2AccountStore sharedStore] accounts] 验证)。

既然我已经保存了 token ,我想在随后的应用程序打开时使用它们,而不是再次向用户请求访问权限。我在这里这样做:

- (NSArray *)allAccounts
{
    NXOAuth2AccountStore *store = [NXOAuth2AccountStore sharedStore];
    NSArray *accounts = [store accountsWithAccountType:kIDMOAuth2AccountType];
    return accounts;
}

以下调用(以获取一些用户详细信息)在用户通过批准流程后立即运行,但在关闭并重新打开应用程序时不起作用。

- (void)requestOAuth2ProtectedDetails
{
    [NXOAuth2Request performMethod:@"GET"
                        onResource:[NSURL URLWithString:@"https://www.googleapis.com/oauth2/v1/userinfo"]
                   usingParameters:nil
                       withAccount:[self allAccounts][0]
               sendProgressHandler:^(unsigned long long bytesSend, unsigned long long bytesTotal) {
                   // e.g., update a progress indicator
               }
                   responseHandler:^(NSURLResponse *response, NSData *responseData, NSError *error){
                       // Process the response
                       if (responseData) {
                           NSError *error;
                           NSDictionary *userInfo = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
                           NSLog(@"%@", userInfo);
                       }
                       if (error) {
                           NSLog(@"%@", error.localizedDescription);
                       }
                   }];
}

我应该如何使用保存的 accessToken/refreshToken 来:

  1. 使用 requestOAuth2ProtectedDetails 查询数据?
  2. 如果需要,使用我保存的 refreshToken 获取更新的 accessToken

这是我遇到的错误:

2014-06-23 09:41:17.040 Connector[8495:60b] Got access token
2014-06-23 09:41:19.296 Connector[8495:60b] *** Assertion failure in -[NXOAuth2Client initWithClientID:clientSecret:authorizeURL:tokenURL:accessToken:tokenType:persistent:delegate:], /Users/ericgross/Documents/Connector/Pods/NXOAuth2Client/Sources/OAuth2Client/NXOAuth2Client.m:82
2014-06-23 09:41:19.300 Connector[8495:60b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'No token or no authorize URL'
*** First throw call stack:
(
    0   CoreFoundation                      0x01c281e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x019a78e5 objc_exception_throw + 44
    2   CoreFoundation                      0x01c28048 +[NSException raise:format:arguments:] + 136
    3   Foundation                          0x015874de -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
    4   Connector                           0x00011456 -[NXOAuth2Client initWithClientID:clientSecret:authorizeURL:tokenURL:accessToken:tokenType:persistent:delegate:] + 502
    5   Connector                           0x00009a59 -[NXOAuth2Account oauthClient] + 841
    6   Connector                           0x0001f30b -[NXOAuth2Request performRequestWithSendingProgressHandler:responseHandler:] + 667
    7   Connector                           0x0001e8d4 +[NXOAuth2Request performMethod:onResource:usingParameters:withAccount:sendProgressHandler:responseHandler:] + 404
    8   Connector                           0x00003eca -[ESGOAuth2Manager requestOAuth2ProtectedDetails] + 266
    9   Connector                           0x00002cba -[ESGOAuth2Manager setup] + 282
    10  Connector                           0x0000214f -[ESGViewController viewDidLoad] + 415
    11  UIKit                               0x0078633d -[UIViewController loadViewIfRequired] + 696
    12  UIKit                               0x007865d9 -[UIViewController view] + 35
    13  UIKit                               0x006a6267 -[UIWindow addRootViewControllerViewIfPossible] + 66
    14  UIKit                               0x006a65ef -[UIWindow _setHidden:forced:] + 312
    15  UIKit                               0x006a686b -[UIWindow _orderFrontWithoutMakingKey] + 49
    16  UIKit                               0x006b13c8 -[UIWindow makeKeyAndVisible] + 65
    17  UIKit                               0x00661bc0 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 2097
    18  UIKit                               0x00666667 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 824
    19  UIKit                               0x0067af92 -[UIApplication handleEvent:withNewEvent:] + 3517
    20  UIKit                               0x0067b555 -[UIApplication sendEvent:] + 85
    21  UIKit                               0x00668250 _UIApplicationHandleEvent + 683
    22  GraphicsServices                    0x02fa7f02 _PurpleEventCallback + 776
    23  GraphicsServices                    0x02fa7a0d PurpleEventCallback + 46
    24  CoreFoundation                      0x01ba3ca5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
    25  CoreFoundation                      0x01ba39db __CFRunLoopDoSource1 + 523
    26  CoreFoundation                      0x01bce68c __CFRunLoopRun + 2156
    27  CoreFoundation                      0x01bcd9d3 CFRunLoopRunSpecific + 467
    28  CoreFoundation                      0x01bcd7eb CFRunLoopRunInMode + 123
    29  UIKit                               0x00665d9c -[UIApplication _run] + 840
    30  UIKit                               0x00667f9b UIApplicationMain + 1225
    31  Connector                           0x0000443d main + 141
    32  libdyld.dylib                       0x02265701 start + 1
    33  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

第一次通过,这个有效:

- (void)performRequestWithSendingProgressHandler:(NXOAuth2ConnectionSendingProgressHandler)progressHandler
                                 responseHandler:(NXOAuth2ConnectionResponseHandler)responseHandler;
{
    NSAssert(self.me == nil, @"This object an only perform one request at the same time.");

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.resource];
    [request setHTTPMethod:self.requestMethod];
    self.connection = [[NXOAuth2Connection alloc] initWithRequest:request
                                                requestParameters:self.parameters
                                                      oauthClient:self.account.oauthClient
                                           sendingProgressHandler:progressHandler
                                                  responseHandler:responseHandler];
    self.connection.delegate = self;

    // Keep request object alive during the request is performing.
    self.me = self;
}

我注意到以下几点:

(lldb) po self.account.oauthClient
<NXOAuth2Client: 0x8f1e760>

但在失败的情况下,会发生这种情况:

(lldb) po self.account.oauthClient
2014-06-23 10:13:25.457 Connector[8678:60b] *** Assertion failure in -[NXOAuth2Client initWithClientID:clientSecret:authorizeURL:tokenURL:accessToken:tokenType:persistent:delegate:], /Users/ericgross/Documents/Connector/Pods/NXOAuth2Client/Sources/OAuth2Client/NXOAuth2Client.m:82
error: Execution was interrupted, reason: internal ObjC exception breakpoint(-3)..
The process has been returned to the state before expression evaluation.

最佳答案

图书馆工作得很好,它会在成功登录后自动保存您的帐户。除非您特别说明,否则不会从帐户存储中删除这些帐户。 例如,我使用它来删除注销时的所有帐户:

NXOAuth2AccountStore* store=[NXOAuth2AccountStore sharedStore];
for (NXOAuth2Account *account in [store accounts]) {
    [store removeAccount:account];
}

当您关闭应用程序时,请注意您没有删除您的帐户。

关于第二件事,我也在寻找解决办法

关于ios - 如何在 NXOAuth2 中使用保存的 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24370996/

相关文章:

objective-c - SInt32 和 << 的问题

objective-c - 使 Objective-C 函数的地址等于 C 函数的指针

c# - ASP.NET MVC 5 和 WebApi 2 身份验证

objective-c - 通过数组属性在 Core Data 中查找对象,在 >10k 元素中高效查找

python - 试图了解 OAuth2 refresh_token 流程 - 不断获得 invalid_grant

java - 如何编辑可扩展服务代理配置文件

ios - 如何在用户触摸屏幕后延迟代码运行

ios - 按住 iOS 中的按钮应显示按钮的标题

iphone - 如何修复 10 分钟后锁定和解锁屏幕时发生的崩溃?

ios - Swift - 动态创建 UIImageView 的动画