hims
hims

Reputation: 77

How to handle error when accessing Google drive using c# .net if I select cancel?

I am trying to access google drive to upload file from c#.net using google APIs. The version my APIs is v3.

I created class AppFlowMetadata to authorize user described as follows.

public class AppFlowMetadata : FlowMetadata
    {
        private static readonly IAuthorizationCodeFlow flow =
           new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
           {
               ClientSecrets = new ClientSecrets
               {
                   ClientId = "Client_ID",
                   ClientSecret = "Secret_ID"
               },
               Scopes = new[] { DriveService.Scope.Drive },
               DataStore = new FileDataStore("Drive.Api.Auth.Store")
           });
        public override string GetUserId(Controller controller)
        {
            // In this sample we use the session to store the user identifiers.
            // That's not the best practice, because you should have a logic to identify
            // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = controller.Session["user"];
            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return user.ToString();

        }
        public override IAuthorizationCodeFlow Flow
        {
            get { return flow; }
        }
    }

Following is the implementation of View on my home controller.

public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken,bool Check=true)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                AuthorizeAsync(cancellationToken);
            if (Check)
            {
                if (result.Credential != null)
                {
                    var service = new DriveService(new BaseClientService.Initializer
                    {
                        HttpClientInitializer = result.Credential,
                        ApplicationName = "ASP.NET MVC Sample"
                    });

                    // YOUR CODE SHOULD BE HERE..
                    // SAMPLE CODE:
                    try
                    {
                        var list = await service.Files.List().ExecuteAsync();
                        ViewBag.Message = "FILE COUNT IS: " + list.Files.Count;
                        return View();
                    }
                    catch (Exception ex)
                    {
                        return View();
                    }
                }
                else
                {
                    return new RedirectResult(result.RedirectUri);
                }
            }
            else`enter code here`
                return View();
        }

Following is my AuthCallbackController implementation

 public class AuthCallbackController : Google.Apis.Auth.OAuth2.Mvc.Controllers.AuthCallbackController
    {
        // GET: AuthCallback

        protected override Google.Apis.Auth.OAuth2.Mvc.FlowMetadata FlowData
        {
            get { return new AppFlowMetadata(); }
        }
    }

It is working fine if I click allow when we ask to access Google drive. But if i click cancel it throws error as shown below.

Error when we click cancel:

Error when we click cancel

To overcome this i added override string authcallback in AppFlowMetadata class.

public override string AuthCallback
        {
            get { return @"/AuthCallback/Index"; }
        }

And added override method in Authcallback controller as below:-

public dynamic Index(AuthorizationCodeResponseUrl authorizationCode, CancellationToken taskCancellationToken)
        {

            var uri = authorizationCode.State;
            if (authorizationCode.Error != null)
                return RedirectToAction("IndexAsync", "Home", new { check = false, cancellationToken = taskCancellationToken });
        }

But if i click allow now it will continuosly showing google sign in screen again and again. How can i handle this. Please Help.

Upvotes: 0

Views: 610

Answers (1)

Hitu Bansal
Hitu Bansal

Reputation: 3137

Remove overide method from AppFlowMetadata class and add overridem method in AuthCallbackController for token error as follows:-

Try this

 protected override ActionResult OnTokenError(TokenErrorResponse errorResponse)
      {
       return RedirectToAction("IndexAsync", "Home", new { errorResp = errorResponse });
      }

Now in index Method of Home controller pass the TokenErrorResponse as parameter and condtion before checking result.credentials. Modify your indexAsync method as below:

public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken, TokenErrorResponse errorResp)
  {
   var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
    AuthorizeAsync(cancellationToken);
   if (errorResp !=null)
   {
    if (result.Credential != null)
    {
     var service = new DriveService(new BaseClientService.Initializer
     {
      HttpClientInitializer = result.Credential,
      ApplicationName = "ASP.NET MVC Sample"
     });

     // YOUR CODE SHOULD BE HERE..
     // SAMPLE CODE:
     try
     {
      var list = await service.Files.List().ExecuteAsync();
      ViewBag.Message = "FILE COUNT IS: " + list.Files.Count;
      return View();
     }
     catch (Exception ex)
     {
      return View();
     }
    }
    else
    {
     return new RedirectResult(result.RedirectUri);
    }
   }
   else
    return View();
  }

Upvotes: 1

Related Questions