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

使用Google Drive API v3和.NET6 Web API上传文件时遇Error 400: redirect_uri_mismatch

解决Google Drive API v3 + .NET6 Web API的redirect_uri_mismatch错误

核心问题

你当前使用的GoogleWebAuthorizationBroker是为桌面应用设计的授权组件,它会自动生成随机本地端口作为重定向URI(比如http://localhost:1234/authorize),这就是错误中出现未知随机URI的原因——每次启动应用端口都不一样,自然和你在云控制台配置的固定URI不匹配。

解决方案

1. 修正Google云控制台的凭据类型

  • 登录Google云控制台,进入项目的凭据页面
  • 删除原有的“桌面应用”类型凭据,创建**“Web应用”类型**的凭据
  • 在“已授权的重定向URI”中添加Web API的回调地址:本地测试可填http://localhost:5000/api/drive/auth-callback(端口对应你的Web API启动端口),生产环境填实际域名的回调路径

2. 替换授权代码(改用Web API适配的授权流)

放弃GoogleWebAuthorizationBroker,改用AuthorizationCodeFlow实现授权,示例代码如下:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/drive")]
public class DriveAuthController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public DriveAuthController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    // 跳转至Google授权页面
    [HttpGet("authorize")]
    public IActionResult Authorize()
    {
        var clientSecrets = new ClientSecrets
        {
            ClientId = _configuration["GoogleDrive:ClientId"],
            ClientSecret = _configuration["GoogleDrive:ClientSecret"]
        };

        var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = clientSecrets,
            Scopes = new[] { DriveService.Scope.Drive },
            DataStore = new FileDataStore("DriveTokenStore", true)
        });

        var redirectUri = Url.Action("AuthCallback", "DriveAuth", null, Request.Scheme);
        var authorizationUrl = flow.CreateAuthorizationCodeRequest(redirectUri).Build();
        
        return Redirect(authorizationUrl.ToString());
    }

    // 处理Google授权回调,获取凭据
    [HttpGet("auth-callback")]
    public async Task<IActionResult> AuthCallback(string code)
    {
        var clientSecrets = new ClientSecrets
        {
            ClientId = _configuration["GoogleDrive:ClientId"],
            ClientSecret = _configuration["GoogleDrive:ClientSecret"]
        };

        var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = clientSecrets,
            Scopes = new[] { DriveService.Scope.Drive },
            DataStore = new FileDataStore("DriveTokenStore", true)
        });

        var redirectUri = Url.Action("AuthCallback", "DriveAuth", null, Request.Scheme);
        var tokenResponse = await flow.ExchangeCodeForTokenAsync("Admin", code, redirectUri, CancellationToken.None);

        // 初始化Drive服务
        var credential = new UserCredential(flow, "Admin", tokenResponse);
        var driveService = new DriveService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = "你的Web API应用名称"
        });

        // 此处可添加文件上传逻辑,或保存凭据供后续使用
        return Ok("授权成功,可执行文件上传操作");
    }
}

3. 清理旧缓存

  • 删除项目目录下的token.json(或代码中credPath指定的文件),避免旧的桌面端授权缓存干扰

关键注意事项

  • 云控制台配置的重定向URI必须和代码中redirectUri完全一致,包括协议(http/https)、端口、路径,不能有多余斜杠或大小写差异
  • 生产环境下,回调地址必须使用HTTPS(Google要求非本地环境的重定向URI必须为HTTPS)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:47:47