使用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
相关产品推荐
相关产品推荐

