gpt4 book ai didi

c# - GoogleWebAuthorizationBroker 无法使用 https//accounts.google.com/o/oauth2/v2/auth 启动浏览器;重定向 uri 不匹配

转载 作者:太空狗 更新时间:2023-10-29 23:53:19 25 4
gpt4 key购买 nike

我遇到了与这个问题完全相同的问题: How do I set return_uri for GoogleWebAuthorizationBroker.AuthorizeAsync?

但是,这个问题在 3 年前就已经回答了,而所提供的答案对我不起作用;我看不到实际设置重定向 uri 的方法。那么问题来了:

static async Task<UserCredential> GetCredential()
{

var clientSecretPath = HttpRuntime.AppDomainAppPath + "client_secret.json";
var credPath = HttpRuntime.AppDomainAppPath + "credentials/GoogleAnalyticsApiConsole/";

UserCredential credential;

using (var stream = new FileStream(clientSecretPath,
FileMode.Open, FileAccess.Read))
{
var secrets = GoogleClientSecrets.Load(stream).Secrets;


credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
secrets,
new[] {AnalyticsReportingService.Scope.Analytics},
"analytics@mysite.com",
CancellationToken.None,
new FileDataStore(credPath, true));

return credential;
}
}

这将返回以下错误:

failed to launch browser with https //accounts.google.com/o/oauth2/v2/auth

它正在尝试使用 redirect_uri = "http://localhost :/authorize"启动 oauth2 页面;当我尝试直接查看它尝试启动的 url 时,页面显示“请求中的重定向 URI:http://localhost:XXXXX/authorize/ 与已注册的重定向 URI 不匹配”

我尝试将 localhost:XXXXX 添加到 Google API 控制台中的授权 url,但下次运行时端口不同,例如 localhost:XXXYY。我的 client_secret.json 文件列出了所有授权的重定向 url,但没有被使用。如何设置重定向 uri 并解决此问题?

最佳答案

我不确定您是在尝试构建本地安装的应用程序还是 asp.net 网络应用程序,但根据您指出的问题,我假设它是一个网络应用程序,这就是我解决它的方法。

首先,GoogleWebAuthorizationBroker 的默认实现是针对本地安装的应用程序。您可以在此 link 中找到它的实现.因此,您的代码可能在本地机器上运行良好,但当托管在网络服务器上时,它可能会永远加载。

因此您需要为 Web 应用程序实现自己的 AuthorizationCodeFlow,如 google 文档中所述。

这就是我在我的 ASP.NET Core MVC 网络应用程序中实现它的方式

public async Task<IActionResult> ConfigureGA(CancellationToken cancellationToken)
{
GoogleAnalyticsModel model = new GoogleAnalyticsModel();
var state = UriHelper.GetDisplayUrl(Request);
var result = await GetCredential(state, cancellationToken);
if (result.Credential != null)
{
using (var svc = new AnalyticsService(
new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "Your App Name"
}))
{

ManagementResource.AccountSummariesResource.ListRequest list = svc.Management.AccountSummaries.List();
list.MaxResults = 1000;
AccountSummaries feed = await list.ExecuteAsync();
model.UserAccounts = feed.Items.ToList();
}

return View(model);
}
else
{
return new RedirectResult(result.RedirectUri);
}

}
private async Task<AuthorizationCodeWebApp.AuthResult> GetCredential(string state, CancellationToken cancellationToken)
{
var userId = userManager.GetUserAsync(User).Result.Id;
var redirectUri = Request.Scheme + "://" + Request.Host.ToUriComponent() + "/authcallback/";
using (var stream = new FileStream("client_secret.json",
FileMode.Open, FileAccess.Read))
{
IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly, AnalyticsReportingService.Scope.AnalyticsReadonly },
DataStore = datastore
});

return await new AuthorizationCodeWebApp(flow, redirectUri, state)
.AuthorizeAsync(userId, cancellationToken);
}
}

我在请求 oauth 凭证(即 GetCredential() 方法)时传递应用程序的状态。

在此方法中,创建您自己的 IAuthorizationCodeFlow 并将您的流程、redirect_uri(您还必须在 Google Developer Console 中设置)和您的应用程序状态传递给 AuthorizationCodeWebApp

接下来您必须实现authcallback Controller 来处理oauth 代码。此代码类似于 google-dotnet-client 库 found here但我采用了相同的代码,因为我正在使用 Microsoft.AspNetCore.Mvc

public class AuthCallbackController : Controller
{
private readonly UserManager<ApplicationUser> userManager;
private readonly IGoogleAnalyticsDataStore datastore;

public AuthCallbackController(UserManager<ApplicationUser> userManager, IGoogleAnalyticsDataStore datastore)
{
this.userManager = userManager;
this.datastore = datastore;
}

protected virtual ActionResult OnTokenError(TokenErrorResponse errorResponse)
{
throw new TokenResponseException(errorResponse);
}
public async virtual Task<ActionResult> Index(AuthorizationCodeResponseUrl authorizationCode,
CancellationToken taskCancellationToken)
{
using (var stream = new FileStream("client_secret.json",
FileMode.Open, FileAccess.Read))
{
IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
DataStore = datastore,
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly, AnalyticsReportingService.Scope.AnalyticsReadonly }
});

if (string.IsNullOrEmpty(authorizationCode.Code))
{
var errorResponse = new TokenErrorResponse(authorizationCode);

return OnTokenError(errorResponse);
}
string userId = userManager.GetUserAsync(User).Result.Id;
var returnUrl = UriHelper.GetDisplayUrl(Request);

var token = await flow.ExchangeCodeForTokenAsync(userId, authorizationCode.Code, returnUrl.Substring(0, returnUrl.IndexOf("?")),
taskCancellationToken).ConfigureAwait(false);

// Extract the right state.
var oauthState = await AuthWebUtility.ExtracRedirectFromState(datastore, userId,
authorizationCode.State).ConfigureAwait(false);

return new RedirectResult(oauthState);
}
}
}

希望这能回答您的问题并且稍微超出问题的范围。

关于c# - GoogleWebAuthorizationBroker 无法使用 https//accounts.google.com/o/oauth2/v2/auth 启动浏览器;重定向 uri 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48065598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com