使用YouTube Data API V3和.NET Core实现桌面应用OAuth授权
在.NET桌面应用中实现YouTube Data API的OAuth2授权
前置准备
- 登录Google Cloud控制台,找到你的项目,在「API和服务」→「凭据」页面创建OAuth 2.0客户端ID,应用类型选择「桌面应用」,创建后下载JSON格式的凭据文件(一般命名为
credentials.json),放到项目目录中。 - 安装所需NuGet包:
Google.Apis.YouTube.v3和Google.Apis.Auth.Mvc
授权流程与API调用实现
桌面应用的OAuth授权采用本地服务器回调机制(Google会将授权码发送到本地临时端口),以下是可直接运行的完整代码示例:
using Google.Apis.Auth.OAuth2; using Google.Apis.Services; using Google.Apis.YouTube.v3; using Google.Apis.YouTube.v3.Data; using System; using System.IO; using System.Threading; namespace YouTubeOAuthDesktopDemo { class Program { // 定义访问个人视频所需的API权限范围 private static readonly string[] Scopes = { YouTubeService.Scope.YoutubeReadonly }; private static readonly string AppName = "YouTube桌面授权演示"; static void Main(string[] args) { UserCredential credential; // 读取OAuth客户端凭据文件 using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { var tokenSavePath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "current-user", CancellationToken.None, new FileDataStore(tokenSavePath, true)).Result; Console.WriteLine($"授权凭据已保存至: {tokenSavePath}"); } // 初始化YouTube服务实例 var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = AppName, }); // 获取当前授权用户的上传视频列表 var channelRequest = youtubeService.Channels.List("contentDetails"); channelRequest.Mine = true; // 指定获取当前用户的频道信息 var channelResponse = channelRequest.Execute(); foreach (var channel in channelResponse.Items) { var uploadsPlaylistId = channel.ContentDetails.RelatedPlaylists.Uploads; var videoListRequest = youtubeService.PlaylistItems.List("snippet"); videoListRequest.PlaylistId = uploadsPlaylistId; videoListRequest.MaxResults = 50; var videoListResponse = videoListRequest.Execute(); foreach (var item in videoListResponse.Items) { Console.WriteLine($"视频标题: {item.Snippet.Title}"); Console.WriteLine($"视频ID: {item.Snippet.ResourceId.VideoId}\n"); } } Console.ReadKey(); } } }
关键细节说明
GoogleWebAuthorizationBroker.AuthorizeAsync会自动唤起浏览器跳转至Google授权页面,用户完成登录授权后,系统会自动处理本地回调并将凭据保存到token.json,后续启动应用无需重复授权。- 如果需要修改视频等操作,需将权限范围替换为
YouTubeService.Scope.Youtube(全权限),根据实际需求选择最小必要权限即可。 - 确保将
credentials.json的「复制到输出目录」属性设置为「如果较新则复制」,避免运行时找不到文件。
内容的提问来源于stack exchange,提问作者user3953989
相关产品推荐
相关产品推荐

