我正在遵循这个教程,我在测试控制器中使用的代码是
[HttpGet("listdrive")]
[GoogleScopedAuthorize(DriveService.ScopeConstants.DriveReadonly)]
public async Task<IActionResult> DriveFileList([FromServices] IGoogleAuthProvider auth)
{
_logger.LogInformation("hello drive");
var 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();
_logger.LogInformation(fileNames.Count.ToString());
return Ok();
}
我还配置了我的服务并完成了依赖项注入,客户端 ID 和密钥应该可以工作,因为我已经在本地桌面应用程序中测试了它们
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 = "aaa";
options.ClientSecret = "bbb";
});
当我调用端点时
listdrive
,这是我得到的堆栈跟踪
[INFORMATION] 2024-02-06T00:07:16.5650763-04:00 [0HN16P1V10T97:00000003] - Authorization failed. These requirements were not met:
2024-02-06T04:07:16.565674114Z DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
2024-02-06T04:07:16.565679663Z Google.Apis.Auth.AspNetCore3.GoogleScopedRequirement
[ERROR] 2024-02-06T00:07:56.4350328-04:00 [0HN16P1V10T86:00000002] - Connection id "0HN16P1V10T86", Request id "0HN16P1V10T86:00000002": An unhandled exception was thrown by the application.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
2024-02-06T04:07:56.436839985Z ---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
2024-02-06T04:07:56.436844239Z ---> System.Threading.Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 60 seconds elapsing.
2024-02-06T04:07:56.436860190Z ---> System.TimeoutException: A task was canceled.
2024-02-06T04:07:56.436863714Z ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
2024-02-06T04:07:56.436866736Z at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
2024-02-06T04:07:56.436869650Z at System.Net.Http.HttpConnectionPool.HttpConnectionWaiter`1.WaitForConnectionAsync(Boolean async, CancellationToken requestCancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
2024-02-06T04:07:56.436875868Z at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
--- End of inner exception stack trace ---
2024-02-06T04:07:56.436890225Z --- End of inner exception stack trace ---
at System.Net.Http.HttpClient.HandleFailure(Exception e, Boolean telemetryStarted, HttpResponseMessage response, CancellationTokenSource cts, CancellationToken cancellationToken, CancellationTokenSource pendingRequestsCts)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
2024-02-06T04:07:56.436904982Z --- End of inner exception stack trace ---
2024-02-06T04:07:56.436908002Z at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
2024-02-06T04:07:56.436917553Z --- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleChallengeAsyncInternal(AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleChallengeAsync(AuthenticationProperties properties)
2024-02-06T04:07:56.436946952Z at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.ChallengeAsync(AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
2024-02-06T04:07:56.436954263Z at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.<>c__DisplayClass0_0.<<HandleAsync>g__Handle|0>d.MoveNext()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
2024-02-06T04:07:56.436963512Z at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
2024-02-06T04:07:56.436973409Z at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
确保您已在项目中添加以下代码。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseHttpsRedirection();
...
app.UseAuthentication();
app.UseAuthorization();
...
}
您似乎缺少一些配置。如果不是,请检查所有软件包的版本,以确保它们与您的项目兼容。例如,使用
.net core 3.1
版本的软件包。
因为默认会安装最新版本,请手动降级到3.1兼容版本。
如果问题仍然存在,请参考此repo看看是否出现问题。