title: Google OAuth Login Error: Invalid credentials
body: <p>I have an iPad application which allows users to login to their Gmail account(s) using OAuth2.  Thus far, the login process and email fetching is successful. However, when the app is closed and then re-opened after a (long) period of time, an error is produced "invalid credentials,' even though previous logins with the same credentials were successful. </p>
  
  <p>Login Flow:
  1) User logs in to gmail using OAuth 2.
  2) User email address and oAuthToken provided by the GTMOAuth2Authentication object are saved to core data for future logins.
  3) IMAP Session is created using saved email address and OAuthToken.</p>
  
  <p>Here is the relevant code</p>
  
  <p><strong>Google Login</strong> </p>
  
  <pre><code>- (void)gmailOAuthLogin
  {
    NSDictionary *googleSettings = [[EmailServicesInfo emailServicesInfoDict] objectForKey:Gmail];
  
    GTMOAuth2ViewControllerTouch *googleSignInController  = 
      [[GTMOAuth2ViewControllerTouch alloc] initWithScope:GmailScope clientID:GmailAppClientID clientSecret:GmailClientSecret keychainItemName:KeychainItemName completionHandler:^(GTMOAuth2ViewControllerTouch *googleSignInController, GTMOAuth2Authentication *auth, NSError *error){
  
     if (error != nil) {
          //handle error
  
     }   else {
  
      [[ModelManager sharedInstance] authenticateWithEmailAddress:[auth userEmail]   
        oAuthToken:[auth accessToken] imapHostname:[googleSettings objectForKey:IMAPHostName] imapPort:[[googleSettings objectForKey:IMAPPort]integerValue] smtpHostname:[googleSettings objectForKey:SMTPHostName] smtpPort:[[googleSettings objectForKey:SMTPPort]integerValue] type:EmailProtocolTypeImapAndSmtpGMail success:^(Account *account) {
  
         //create IMAP session using above arguments
  
          } failure:^(NSError *error) {
              //handle error                       
          }];
  
          }
      }];
  
        [self presentGoogleSignInController:googleSignInController];
      }
  </code></pre>
  
  <p><strong>Create IMAP Session Using MailCore2</strong></p>
  
  <pre><code>- (void)authenticateWithEmailAddress:(NSString *)emailAddress password:(NSString *)password oAuthToken:(NSString *)oAuthToken imapHostname:(NSString *)imapHostname imapPort:(NSInteger)imapPort smtpHostname:(NSString *)smtpHostname smtpPort:(NSInteger)smtpPort success:(void (^)())success failure:(void (^)(NSError *))failure
  {
    self.imapSession = [[MCOIMAPSession alloc] init];
    self.imapSession.hostname = imapHostname;
    self.imapSession.port = imapPort;
    self.imapSession.username = emailAddress;
    self.imapSession.connectionType =  MCOConnectionTypeTLS;
    self.imapSession.password = nil;
    self.imapSession.OAuth2Token = oAuthToken;
    self.imapSession.authType = nil != oAuthToken ? MCOAuthTypeXOAuth2 :      
    self.imapSession.authType;
  
    [self.imapSession setConnectionLogger:^(void * connectionID, MCOConnectionLogType type,    
  NSData * data){
  NSLog(@"MCOIMAPSession: [%i] %@", type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
  
    self.smtpSession = [[MCOSMTPSession alloc] init];
    self.smtpSession.hostname = smtpHostname;
    self.smtpSession.port = smtpPort;
    self.smtpSession.username = emailAddress;
    self.smtpSession.connectionType = MCOConnectionTypeTLS;
    self.smtpSession.password = nil;
    self.smtpSession.OAuth2Token = oAuthToken;
    self.smtpSession.authType = nil != oAuthToken ? MCOAuthTypeXOAuth2 :   
    self.smtpSession.authType;
  
    [self.smtpSession setConnectionLogger:^(void * connectionID, MCOConnectionLogType type, NSData * data){
      NSLog(@"MCOSMTPSession: [%i] %@", type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
  
    [[self.imapSession checkAccountOperation] start:^(NSError *error) {
      if (nil == error) {
        success();
      } else {
        failure(error); //FAILS WITH INVALID CREDENTIALS ERROR
      }
    }];
  }
  </code></pre>
  
  <p>Once again, the above code works fine, unless the application has not been used in some time. I was not sure if I needed to refresh the OAuthToken or not, so I tried doing the following on launch of the application:</p>
  
  <pre><code>GTMOAuth2Authentication *auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:KeychainItemName clientID:GmailAppClientID clientSecret:GmailClientSecret];
  
    BOOL canAuthorize = [auth canAuthorize]; //returns YES
    NSDictionary *googleSettings = [[EmailServicesInfo emailServicesInfoDict] objectForKey:Gmail];
  
    [[ModelManager sharedDefaultInstance] authenticateWithEmailAddress:[auth userEmail] oAuthToken:[auth refreshToken] imapHostname:[googleSettings objectForKey:IMAPHostName] imapPort:[[googleSettings objectForKey:IMAPPort]integerValue] smtpHostname:[googleSettings objectForKey:SMTPHostName] smtpPort:[[googleSettings objectForKey:SMTPPort]integerValue] type:EmailProtocolTypeImapAndSmtpGMail success:^(Account *account) {
  
      //create IMAP session
  
  } failure:^(NSError *error) {
    NSLog(@"failure %@", error);
  }];
  </code></pre>
  
  <p>But I still get the same error. I have no idea why the OAuth token stops working or how to resolve this. Since the user is able to save multiple accounts, I am wondering if I need to save the refresh token for each account in core data and use that if the access token stops working? </p>