Home > front end >  ASP.NET MVC C# Google Drive API Redirect mismatch URI
ASP.NET MVC C# Google Drive API Redirect mismatch URI

Time:10-06

For reference, I followed this site https://qawithexperts.com/article/asp-net/upload-file-to-google-drive-using-google-drive-api-in-aspnet/236 on how to upload a file to Google Drive in a Web Application.

This is my code to get the DriveService


public static string[] Scopes = { Google.Apis.Drive.v3.DriveService.Scope.Drive };

public static DriveService GetService()
{
    //get Credentials from client_secret.json file 
    UserCredential credential;
    DriveService service = null;

    //Root Folder of project
    var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/");
    try
    {
        using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
        {
            String FolderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/");
            String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(FilePath, true)).Result;
        }
        //create Drive API service.
        service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "GoogleDriveMVCUpload",
        });
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine(e.StackTrace);
        System.Diagnostics.Debug.WriteLine(e.Message);
        System.Diagnostics.Debug.WriteLine(e.InnerException);

    }
    return service;
            
}

The problem occurs at getting the credential from GoogleWebAuthorizationBroker.AuthorizeAsync. When that line runs, I would be redirected to this link (The port of the redirect URI http://127.0.0.1:52829/authorize/ changes everytime I run this code).

I have looked into Google's Error docs and other stack overflow explaining that I must add the redirect URI on the console in which I did shown here but it still has the redirect_uri_mismatch error. When I do just open the redirect URI (example : http://127.0.0.1:52829/authorize/) given in the error, I get the following

image

. But then an exception would be thrown

Exception thrown: 'System.AggregateException' in mscorlib.dll
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at .........
One or more errors occurred.
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:""
   at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext()
**service** was null.

and I couldn't find much about this specific exception error :

Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:"" but I believe this is because of the redirect mismatch URI problem.

For more information: The current link of the web application is http://localhost:61506 and the link when I run the code above is at http://localhost:61506/AutoFileTransfer/Index

So I don't really know why I get this redirect mismatch URI error nor do I know how to solve the Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:"" problem either.

CodePudding user response:

The first problem you are having is that you are using GoogleWebAuthorizationBroker.AuthorizeAsync which is designed to work with installed applications only its not going to work with Asp .net

For asp .net MVC you should be doing the following

using System;
using System.Web.Mvc;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Drive.v2;
using Google.Apis.Util.Store;

namespace Google.Apis.Sample.MVC4
{
    public class AppFlowMetadata : FlowMetadata
    {
        private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "PUT_CLIENT_ID_HERE",
                        ClientSecret = "PUT_CLIENT_SECRET_HERE"
                    },
                    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; }
        }
    }
}
      

The official sample can be found web-applications-asp.net-mvc

The second issue you have is that your IDE is changing the ports on you. You need to fix it so that it uses a static port then you can add your redirect uri properly. How to create Google Oauth2 web application credentials in 2021. Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications.

As for that example you are following the author may have gotten it to work on local host but it will never work hosted as a website as GoogleWebAuthorizationBroker.AuthorizeAsync will open the browser window on the machine that its running on. This being a web server will never work.

  • Related