HttpListenerException”;访问被拒绝”;使用GoogleWebAuthorizationBroker
本文关键字:使用 GoogleWebAuthorizationBroker 拒绝 访问 HttpListenerException | 更新日期: 2023-09-27 17:58:32
我正在尝试使用Azure托管的web应用程序进行OAuth2,但我不能使用服务帐户(这里有很多解决方案,但它们都坚持使用服务帐户/证书),而我需要用户通过谷歌进行身份验证和授权。
代码:
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets { ClientId = _clientId, ClientSecret = _clientSecret },
scopes,
User.Identity.Name,
CancellationToken.None,
new FileDataStore("GA.Auth.Store")) /* tried this to be null as well */
.Result;
var service = new AnalyticsService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Analytics API Sample"
});
它在本地工作,但在部署为Azure web应用程序时会出现此异常:
[HttpListenerException (0x5): Access is denied]
Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +82
Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task) +76
Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() +233
我猜GoogleWebAuthorizationBroker.AuthorizationAsync正在尝试建立一个http侦听器,这在Azure web应用程序中是不可能的。
我尝试使用Azure web应用程序身份验证。这确实对用户进行了身份验证,但我如何检索经过身份验证的用户来授权他对抗谷歌?
BTW:因为我需要GA实时,所以我一直使用GA Reporting v3库。
GoogleWebAuthorizationBroker.AuthorizeAsync是为已安装的应用程序设计的,因为它将尝试在服务器上打开web浏览器窗口以获得同意。
你应该以网络为例。
public void ConfigureServices(IServiceCollection services)
{
...
// 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};
});
}