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

Google Drive API 400重定向URI不匹配:Blazor Server端口动态变化问题咨询

解决Blazor Server中Google Drive API认证的Redirect_uri_mismatch(动态端口问题)

1. 固定Blazor Server调试端口

动态端口是导致重定向URI不匹配的核心原因。修改项目根目录下的launchSettings.json,将applicationUrl设置为固定端口:

"profiles": {
  "YourBlazorServerApp": {
    "commandName": "Project",
    "dotnetRunMessages": true,
    "launchBrowser": true,
    "applicationUrl": "https://localhost:5001;http://localhost:5000",
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    }
  }
}

保存后重启调试,端口将固定为5000(HTTP)和5001(HTTPS)。

2. 更新Google Cloud Console的重定向URI

GoogleWebAuthorizationBroker默认使用/authorize作为回调路径,需在Google控制台添加以下两个重定向URI:

  • http://localhost:5000/authorize
  • https://localhost:5001/authorize
    添加完成后,重新下载client_secret.json并替换项目中的对应文件。

3. 优化认证代码(适配Blazor Server场景)

原代码存在Scope定义与实际使用不一致的问题,同时GoogleWebAuthorizationBroker默认的文件存储逻辑在Blazor Server多用户场景下易冲突,建议调整为内存存储并统一Scope:

@code {
    // 根据业务需求统一Scope
    private readonly string[] _scopes = { DriveService.Scope.DriveFile };
    private const string _applicationName = "Drive API Blazor Backend";
    private DriveService _driveService;

    protected override async Task OnInitializedAsync()
    {
        var clientSecrets = await GoogleClientSecrets.FromFileAsync("client_secret.json");

        // 使用MemoryDataStore避免多用户凭证冲突(开发环境)
        var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            clientSecrets.Secrets,
            _scopes,
            "user",
            CancellationToken.None,
            new MemoryDataStore());

        _driveService = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = _applicationName
        });

        // 测试文件列表功能
        var fileList = await _driveService.Files.List().ExecuteAsync();
        Console.WriteLine($"已获取 {fileList.Files.Count} 个文件");
    }
}

4. 生产环境部署注意事项

部署到生产服务器时,需将重定向URI替换为你的正式域名(例如https://your-domain.com/authorize),同时替换MemoryDataStore为数据库等持久化存储方案,确保用户凭证安全且可跨会话复用。

内容的提问来源于stack exchange,提问作者Tim Cadieux

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:22:14