ASP.NET MVC C# Google 驱动器 API 重定向不匹配的 URI
ASP.NET MVC C# Google Drive API Redirect mismatch URI
作为参考,我关注了这个网站 https://qawithexperts.com/article/asp-net/upload-file-to-google-drive-using-google-drive-api-in-aspnet/236 如何在 Web 应用程序中将文件上传到 Google 驱动器。
这是我获取 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;
}
从 GoogleWebAuthorizationBroker.AuthorizeAsync 获取凭据时出现问题。当那行 运行s 时,我将被重定向到
this link (The port of the redirect URI http://127.0.0.1:52829/authorize/ 每次我 运行 这段代码都会改变。
我查看了 Google 的错误文档和其他堆栈溢出,解释说我必须在错误中给出的控制台上添加重定向 URI 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/),我明白了以下
。但随后会抛出异常
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.
我找不到关于这个特定异常错误的太多信息:
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:"" but I believe this is because of the redirect mismatch URI problem.
更多信息:Web应用程序的当前link是http://localhost:61506和link当我运行上面的代码在http:/ /localhost:61506/AutoFileTransfer/Index
所以我真的不知道为什么会收到此重定向不匹配 URI 错误,也不知道如何解决
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:""
也有问题。
您遇到的第一个问题是您使用的 GoogleWebAuthorizationBroker.AuthorizeAsync
仅适用于已安装的应用程序,不适用于 Asp .net
对于 asp .net MVC,您应该执行以下操作
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; }
}
}
}
可以找到官方样本web-applications-asp.net-mvc
您遇到的第二个问题是您的 IDE 正在更改您的端口。您需要修复它以便它使用静态端口,然后您可以正确添加重定向 uri。 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.
至于你所关注的那个例子,作者可能已经让它在本地主机上工作,但它永远不会作为网站托管,因为 GoogleWebAuthorizationBroker.AuthorizeAsync 将在机器上打开浏览器 window它 运行 上。这是一个网络服务器将永远无法工作。
作为参考,我关注了这个网站 https://qawithexperts.com/article/asp-net/upload-file-to-google-drive-using-google-drive-api-in-aspnet/236 如何在 Web 应用程序中将文件上传到 Google 驱动器。
这是我获取 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;
}
从 GoogleWebAuthorizationBroker.AuthorizeAsync 获取凭据时出现问题。当那行 运行s 时,我将被重定向到 this link (The port of the redirect URI http://127.0.0.1:52829/authorize/ 每次我 运行 这段代码都会改变。
我查看了 Google 的错误文档和其他堆栈溢出,解释说我必须在错误中给出的控制台上添加重定向 URI 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/),我明白了以下
。但随后会抛出异常
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.
我找不到关于这个特定异常错误的太多信息:
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:"" but I believe this is because of the redirect mismatch URI problem.
更多信息:Web应用程序的当前link是http://localhost:61506和link当我运行上面的代码在http:/ /localhost:61506/AutoFileTransfer/Index
所以我真的不知道为什么会收到此重定向不匹配 URI 错误,也不知道如何解决
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:""
也有问题。
您遇到的第一个问题是您使用的 GoogleWebAuthorizationBroker.AuthorizeAsync
仅适用于已安装的应用程序,不适用于 Asp .net
对于 asp .net MVC,您应该执行以下操作
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; }
}
}
}
可以找到官方样本web-applications-asp.net-mvc
您遇到的第二个问题是您的 IDE 正在更改您的端口。您需要修复它以便它使用静态端口,然后您可以正确添加重定向 uri。 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.
至于你所关注的那个例子,作者可能已经让它在本地主机上工作,但它永远不会作为网站托管,因为 GoogleWebAuthorizationBroker.AuthorizeAsync 将在机器上打开浏览器 window它 运行 上。这是一个网络服务器将永远无法工作。