Dot-Net核心3.1中的GoogleWebAuthorizationBroker.AuthorizeAsync访问被



它在本地机器中运行良好,但在Azure中部署后,我遇到了一个错误。

在Google.Apis.Auth.Outh2.LocalServerCodeReceiver.StartListener((的System.Net.HttpListener.SetupV2Config(字符串userId,CancellationToken taskCancellationToken(在Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthenticationAsync(初始化程序初始值设定项,IEnumerable1 scopes, String user, CancellationToken taskCancellationToken, IDataStore dataStore, ICodeReceiver codeReceiver) at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(ClientSecrets clientSecrets, IEnumerable1 1作用域,字符串用户,CancellationToken taskCancellationToken,IDataStore数据存储,ICodeReceiver codeReceiver(的Salon.Web.Factories.GmailHelperFactory.GetGmailCode((在D:\Application\ArtSolutions\SalonSoftware\ArtSolutions.Salon.Web\Factories\GmailHelperFactory.cs:line 368

public async Task GetGmailCode()
{
var userSession = _httpContextAccessor.HttpContext.Session.Get<UserSession>(CommonWebHelper.S_USERSESSION);
try
{
string[] Scopes = {
GmailService.Scope.GmailReadonly,
GmailService.Scope.MailGoogleCom,
GmailService.Scope.GmailModify
};
UserCredential credential;
using (var stream = new FileStream($"client_secret.{_webHostEnvironment.EnvironmentName}.json", FileMode.Open, FileAccess.Read))
{
//string credPath = Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string credPath = Path.Combine(_webHostEnvironment.WebRootPath, "credentials");
await _logService.InsertInfoLogAsync(userSession.Id, (int)ModuleFeatures.SalesInvoice, credPath);
//credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
DsAuthorizationBroker.RedirectUri = _appSettings.Authentication.Google.AuthCodeRedirectURL;
//await _logService.InsertInfoLogAsync(userSession.Id, (int)ModuleFeatures.SalesInvoice, DsAuthorizationBroker.RedirectUri);
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromStream(stream).Secrets,
Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true));
}
}
catch (Exception ex)
{
await _logService.InsertErrorLogAsync(userSession.Id, (int)ModuleFeatures.SalesInvoice, ex);
}
}

GoogleWebAuthorizationBroker.AuthorizeAsync

是为已安装的应用程序设计的,这意味着它将打开运行代码的机器上的web浏览器窗口。如果您的web应用程序试图打开web服务器上的web服务器,但无法正常工作。

GoogleWebAuthorizationBroker.AuthorizeAsync默认使用FileDataStore。Azure不允许您写入%appData%

对于asp网络,你需要使用类似于的东西

程序.cs

// This configures Google.Apis.Auth.AspNetCore3 for use in this app.
services
.AddAuthentication(o =>
{
// This forces challenge results to be handled by Google OpenID Handler, so there's no
// need to add an AccountController that emits challenges for Login.
o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// This forces forbid results to be handled by Google OpenID Handler, which checks if
// extra scopes are required and does automatic incremental auth.
o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// Default scheme that will handle everything else.
// Once a user is authenticated, the OAuth2 token info is stored in cookies.
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = {YOUR_CLIENT_ID};
options.ClientSecret = {YOUR_CLIENT_SECRET};
});
}

控制器

/// <summary>
/// Lists the authenticated user's Google Drive files.
/// Specifying the <see cref="GoogleScopedAuthorizeAttribute"> will guarantee that the code
/// executes only if the user is authenticated and has granted the scope specified in the attribute
/// to this application.
/// </summary>
/// <param name="auth">The Google authorization provider.
/// This can also be injected on the controller constructor.</param>
[GoogleScopedAuthorize(DriveService.ScopeConstants.DriveReadonly)]
public async Task<IActionResult> DriveFileList([FromServices] IGoogleAuthProvider auth)
{
GoogleCredential cred = await auth.GetCredentialAsync();
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = cred
});
var files = await service.Files.List().ExecuteAsync();
var fileNames = files.Files.Select(x => x.Name).ToList();
return View(fileNames);
}

我有一个YouTube视频如何获得谷歌用户档案信息,用C#。以及一篇博客文章Asp.netcore3和谷歌登录,这可能也会有所帮助。

最新更新