You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 7集成Google Drive API时GetFallbackPolicyAsync方法缺失错误解决

解决.NET Core 7集成Google Drive API时的GoogleScopedPolicyProvider方法缺失错误

问题根源

这个错误是因为ASP.NET Core 7对IAuthorizationPolicyProvider接口新增了GetFallbackPolicyAsync方法,但部分版本的Google.Apis.Auth.AspNetCore包未实现该方法;即使使用最新包,也可能存在包版本不兼容或混用认证组件的问题。

解决方案步骤

1. 统一并更新依赖包版本

确保所有Google相关的认证和Drive API包版本兼容.NET 7,避免混用官方和微软的Google认证组件:

  • 卸载Microsoft.AspNetCore.Authentication.Google(如果已安装)
  • 安装/更新以下包到最新兼容版本(推荐5.10.0及以上):
Install-Package Google.Apis.Auth.AspNetCore -Version 5.10.0
Install-Package Google.Apis.Drive.v3

2. 正确配置认证与授权

在Program.cs中完成Google认证、授权策略及Drive服务的配置,确保未认证用户自动跳转到Google登录页:

var builder = WebApplication.CreateBuilder(args);

// 配置认证:Cookie作为默认方案,Google作为挑战方案
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
    // 从配置文件读取Google OAuth凭证
    options.ClientId = builder.Configuration["Google:ClientId"];
    options.ClientSecret = builder.Configuration["Google:ClientSecret"];
    // 添加Google Drive所需权限(按需调整,比如DriveReadonly、Drive等)
    options.Scope.Add(DriveService.Scope.DriveReadonly);
    options.SaveTokens = true; // 保存访问令牌,供后续Drive API调用使用
});

// 配置授权:默认策略要求用户已认证
builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

// 注册Drive服务,使用当前用户的访问令牌初始化
builder.Services.AddScoped<DriveService>(sp =>
{
    var httpContextAccessor = sp.GetRequiredService<IHttpContextAccessor>();
    var accessToken = httpContextAccessor.HttpContext.GetTokenAsync("access_token").Result;

    var initializer = new BaseClientService.Initializer
    {
        HttpClientInitializer = new UserCredential(
            new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = builder.Configuration["Google:ClientId"],
                        ClientSecret = builder.Configuration["Google:ClientSecret"]
                    }
                }),
            "current-user",
            new TokenResponse { AccessToken = accessToken }),
        ApplicationName = "你的应用名称"
    };

    return new DriveService(initializer);
});

builder.Services.AddControllersWithViews();
builder.Services.AddHttpContextAccessor();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
// 注意中间件顺序:先认证,再授权
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

3. 手动适配缺失方法(如果仍报错)

若更新包后仍出现GetFallbackPolicyAsync缺失错误,可自定义策略提供者继承GoogleScopedPolicyProvider并实现该方法:

public class CustomGooglePolicyProvider : GoogleScopedPolicyProvider
{
    public CustomGooglePolicyProvider(IOptions<AuthorizationOptions> options) : base(options)
    {
    }

    public override Task<AuthorizationPolicy?> GetFallbackPolicyAsync()
    {
        // 返回默认的 fallback 策略,或按需自定义
        return Task.FromResult<AuthorizationPolicy?>(new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build());
    }
}

然后在Program.cs中替换默认的策略提供者:

builder.Services.AddSingleton<IAuthorizationPolicyProvider, CustomGooglePolicyProvider>();

额外注意事项

  • 确保Google Cloud Console中已正确创建OAuth 2.0客户端ID,且授权回调地址与应用匹配(如本地开发时的https://localhost:xxxx/signin-google)
  • appsettings.json中需配置Google:ClientId和Google:ClientSecret两个字段
  • 避免同时引用Google.Apis.Auth.AspNetCore和Microsoft.AspNetCore.Authentication.Google,防止组件冲突

内容的提问来源于stack exchange,提问作者Rahul Goyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:13:29