我们正在更新 Data API,以便与 YouTube 统计 Shorts 短视频观看次数的方式保持一致。
了解详情
从 ClientLogin 迁移到 OAuth 2.0
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
Ikai LanYouTube Developer Relations – June 2013
YouTube API 使用 OAuth 2.0 对用户请求进行授权。我们经常被问到,未来是否会在 YouTube API 中添加对 ClientLogin 身份验证或类似功能的支持。不过,我们已于 2012 年 4 月 20 日正式弃用 ClientLogin,并且没有添加此类机制的计划。
我们认为,支持各种 OAuth 2.0 授权流程对 YouTube 用户而言比 ClientLogin 更好,原因有很多。这些流程支持桌面应用、仅限 Web 的应用、原生移动应用,甚至支持在没有复杂输入机制的设备(例如电视)上运行的应用,而使用 ClientLogin 很难实现这些用例。此外,我们发现 ClientLogin 会给许多开发者发布后带来更多麻烦,我们在博文 ClientLogin #FAIL 中介绍了其中的一些问题。
将 OAuth 2.0 用于服务器端独立脚本
许多开发者使用 ClientLogin 来授权在没有浏览器的服务器上运行的命令行脚本。使用 OAuth 2.0 时,几乎总会涉及浏览器,但如果您使用 Google Play Services 通过 GoogleAuthUtil. 提取令牌,则不受此限制
在仅限网页的流程中,如果网站想要代表用户发出经过身份验证的 API 调用,则必须将用户重定向到 google.com 身份验证页面,其中说明应用尝试访问的内容。然后,该 Web 应用会收到一个令牌,并使用该令牌进行 API 调用。然后,用户可以随时使用 connected apps and sites 页面撤消应用的访问权限。
我们的 Python 代码示例演示了命令行脚本如何启动浏览器并从终端窗口发出 API 调用、创建本地服务器以在授权重定向后监听代码,以及自动保存令牌以供日后进行 API 调用。下面的视频展示了此功能的运作方式:
使用的令牌是 ASCII 字符串。如果是 offline
令牌,则是可移植的。使用检索到的令牌,您将能够在桌面上运行脚本,然后在没有 GUI 的远程服务器上复制并使用该代码(前提是该代码使用相同的客户端 ID 和密钥实例化 OAuth 2.0 客户端)。除了 Python 之外,适用于其他编程语言的 Google API 客户端库还提供了用于管理令牌的辅助方法,这些令牌可在客户端之间共享,甚至可直接在较低级别的 HTTP 库中使用(在客户端标头中或作为网址参数)。
以下是使用离线令牌的服务器端脚本示例:
- 一个守护程序,用于监控目录,以便自动将新视频上传到 YouTube
- 一个 Cron 作业,用于每天使用新内容更新播放列表
- 此脚本通过 YouTube Analytics API 监控视频数据,并在发生特定事件(例如总观看时长超出限制)时通知频道管理员。请注意,在这种情况下,OAuth 2.0 是唯一受支持的授权方法,因为 Google Analytics API 不支持 ClientLogin。
长效访问令牌部分详细介绍了如何生成可用于服务器端进程的离线令牌。
客户端 ID 和客户端密钥最佳实践
共享相同客户端 ID 和密钥对的任何代码都可以使用相同的访问令牌。最好将对客户端 ID 和客户端密钥的访问权限限制为仅限在贵组织的机器和设备上运行的代码。
请勿将您的客户端 ID 和客户端密钥包含在原生移动应用代码中。所有通过移动设备进行 OAuth 2.0 身份验证的开发者都应使用“已安装的应用”客户端 ID,该 ID 会要求提供更多信息,以验证请求是否仅来自您的团队发布的应用。

在 Android 设备上,系统会使用软件包名称和签名证书哈希的组合来标识您的应用,而不是使用客户端 ID 和客户端密钥。在 iOS 设备上,系统会使用软件包 ID 和应用商店 ID。如需了解如何检索此类信息,请参阅 Google API Console 帮助页面中的官方文档。
服务账号不适用于 YouTube API
服务账号不适用于 YouTube Data API 调用,因为服务账号需要关联的 YouTube 频道,而您无法将新频道或现有频道与服务账号相关联。如果您使用服务账号调用 YouTube Data API,API 服务器会返回错误,并将错误类型设置为 unauthorized
,将原因设置为 youtubeSignupRequired
。
对 YouTube API 的离线/长时访问
OAuth 2.0 有短期有效令牌和长期有效令牌。对于一次性操作,短期有效的访问令牌是最佳选择。这些令牌会在授予后不久过期。对于长时间运行的作业,您可能需要考虑获取刷新令牌,该令牌用于提取短期有效的访问令牌。
为确保您的应用收到的是长效刷新令牌,而不是短效访问令牌,请在创建客户端 ID 时使用“已安装的应用”流程,并为“已安装的应用类型”值选择 Other
:

建议您针对此使用情形使用“已安装的应用”流程。如果您需要在 Web 应用中长期访问 YouTube API,可以在初始授权请求或客户端配置中将 access_type
参数设置为 offline
并将 approval_prompt
参数设置为 force
,以检索长期访问权限。某些客户端库会管理提取和刷新访问令牌。如果您有兴趣编写自己的自定义授权代码,可以参阅我们在 Google Code 博客上发布的博文,以此为基础编写代码。
在手机、平板电脑和其他设备上使用 OAuth 2.0
在编写 Android 应用时,开发者可以利用 Google Play services 来处理授权详情。Google Play 服务为所有 Google API 提供了标准授权流程,包括 YouTube 平台的 API。与使用 ClientLogin 的自定义身份验证相比,这种方法可为 Android 应用用户提供远远更出色的用户体验。

在 iOS 设备上,Google 提供了两种选项:
对于旨在充当“第二屏幕”设备的设备,或者没有易于使用的输入机制的电视等设备,适用于设备的 OAuth 2.0 是首选方法。适用于设备的 OAuth 2.0 的工作原理是,在需要授权请求时向用户显示唯一代码。此时,系统会要求用户在其他设备(例如笔记本电脑或手机)上浏览到 http://google.com/device,然后输入唯一代码。应用会显示一个如下所示的界面:

当用户在另一部设备上输入代码时,应用会定期轮询以查看是否已输入代码。完成后,它会检索用于进行 API 调用的令牌。如需查看其实际效果,请查看演示版,该演示版可在任何支持网络的设备上运行。该 API 本身不依赖于平台,因此非常适用于不具备 Web 呈现功能的设备。我们已发布了Python 示例代码,供您参考。
摘要
OAuth 2.0 授权为需要 YouTube 授权的开发者提供了灵活性。熟悉 ClientLogin 的开发者可能会发现,开始时需要稍微多做一些工作才能将应用设置为使用 OAuth 2.0,但完成移植后,OAuth 2.0 应用便可在多个平台上为最终用户提供更高的灵活性、安全性和易用性。
如果您对 OAuth 2.0 或本文中的任何示例还有其他疑问,欢迎随时在 StackOverflow 上使用 youtube-api 标签提问。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-02-06。
[null,null,["最后更新时间 (UTC):2025-02-06。"],[[["\u003cp\u003eYouTube APIs use OAuth 2.0 for user request authorization, and ClientLogin has been officially deprecated with no plans for future support.\u003c/p\u003e\n"],["\u003cp\u003eOAuth 2.0 offers broader support for various application types, including desktop, web, mobile, and devices with limited input capabilities, providing superior flexibility compared to ClientLogin.\u003c/p\u003e\n"],["\u003cp\u003eServer-side scripts can leverage OAuth 2.0 through offline tokens, allowing for portability and persistent access across different environments without a constant need for browser interaction.\u003c/p\u003e\n"],["\u003cp\u003eFor mobile applications, it is crucial to avoid including client ID and secret in native code, instead using mechanisms like package names and certificate hashes for Android, or bundle and app store IDs for iOS.\u003c/p\u003e\n"],["\u003cp\u003eService accounts will not work with YouTube APIs and will return an error as they cannot be connected to YouTube channels.\u003c/p\u003e\n"]]],["YouTube APIs use OAuth 2.0 for authorization, having deprecated ClientLogin. OAuth 2.0 supports various application types, including server-side scripts, web apps, and mobile apps. Server-side scripts use \"offline\" tokens for long-lived access, enabling tasks like automated video uploads and playlist updates. Client ID and secrets should be restricted to internal code. Mobile apps use unique identifiers, while \"second screen\" devices use a code-based authorization. OAuth 2.0 offers superior security and flexibility across platforms.\n"],null,["# Move from ClientLogin to OAuth 2.0\n\n*Ikai Lan, YouTube Developer Relations -- June 2013*\nYouTube APIs use [OAuth 2.0](https://developers.google.com/youtube/v3/guides/authentication) to authorize user requests. We are frequently asked whether we will add support for ClientLogin authentication or something similar in YouTube APIs going forward. However, we [officially deprecated ClientLogin as of April 20, 2012](https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin), and there are no plans to add such a mechanism.\n\nThere are numerous reasons why we believe supporting various flows of OAuth 2.0 authorization is better for YouTube users than ClientLogin. These flows support use cases for desktop applications, web-only applications, native mobile applications, and even applications that run on devices like televisions that don't have sophisticated input mechanisms, something which is difficult to do using ClientLogin. Also, we've found that ClientLogin causes more headaches post-launch for many developers, some of which we describe in our blog post, [ClientLogin #FAIL](http://apiblog.youtube.com/2011/03/clientlogin-fail.html).\n\nUsing OAuth 2.0 for server-side, standalone scripts\n---------------------------------------------------\n\nMany developers use ClientLogin to authorize command-line scripts that run on servers without a browser. With OAuth 2.0, there's almost always going to be a browser involved -- the exception being when you're working on an Android application that uses Google Play Services to fetch tokens via [GoogleAuthUtil.](http://developer.android.com/reference/com/google/android/gms/auth/GoogleAuthUtil.html)\n\nIn a [web-only flow](https://developers.google.com/accounts/docs/OAuth2WebServer), a website that wants to make authenticated API calls on behalf of a user must redirect the user to a google.com authentication page that explains what the application is trying to access. The web application then receives a token, which it uses to make API calls. The user can then revoke the application's access at any time using the [connected apps and sites](https://accounts.google.com/IssuedAuthSubTokens) page.\n\nOur [Python code samples](https://developers.google.com/youtube/v3/code_samples/python) demonstrate how command-line scripts can launch a browser and make API calls from a terminal window, create a local server to listen for the code after the authorization redirect, and automatically save a token for future API calls. A video of this in action is below:\n\nThe token used is an ASCII string. If it is an `offline` token, it is *portable* . Using the retrieved token, you will be able to run the script on your desktop, then copy and use the code on a remote server without a GUI, provided that code instantiates an OAuth 2.0 client with the same client ID and secret. In addition to Python, the [Google API client libraries](https://developers.google.com/discovery/libraries) for other programming languages also provide helper methods for managing tokens, which can be shared between clients and even used in lower-level HTTP libraries directly [in a client header or as a URL parameter](https://developers.google.com/accounts/docs/OAuth2UserAgent#callinganapi).\n\nSome examples of server-side scripts that use offline tokens:\n\n- A daemon that monitors a directory for new videos to automatically upload to YouTube\n- A cron job that that updates playlists daily with new content\n- A script that monitors video data via the [YouTube Analytics API](https://developers.google.com/youtube/analytics/) and notifies channel managers when certain events take place, such as aggregate watch time exceeding a limit. Note that in this case, OAuth 2.0 is the only supported authorization method because the Analytics API does not support ClientLogin.\n\nThe section on [long-lived access tokens](#offline_access) provides more detail about how to generate the offline tokens that can be used for server side processes.\n\nClient ID and client secret best practices\n------------------------------------------\n\nAny code that shares the same client ID and secret pair can use the same access tokens. It's best to restrict access to client ID and client secrets to code that runs on machines and devices within your organization.\n\nDo not include your client ID and client secret as part of your native mobile applications code. All developers doing OAuth 2.0 authentication from a mobile device should make use of the \"Installed application\" client ID, which asks for additional information to verify that the request is coming only from an application released by your team.\n\nOn Android devices, instead of using a client ID and client secret, your application is identified using a combination of the package name and a signing certificate hash. On iOS devices, the bundle ID and the app store ID are used. The official documentation on retrieving this information can be found on the [Google API Console help page](https://developers.google.com/console/help/#installed_applications).\n\nService Accounts do not work with the YouTube API\n-------------------------------------------------\n\nService accounts do not work for YouTube Data API calls because service accounts require an associated YouTube channel, and you cannot associate new or existing channels with service accounts. If you use a service account to call the YouTube Data API, the API server [returns an error](https://developers.google.com/youtube/v3/docs/errors#youtube.api.RequestContextError-unauthorized-youtubeSignupRequired) with the error type set to `unauthorized` and the reason set to `youtubeSignupRequired`.\n\nOffline/long-lived access to the YouTube API\n--------------------------------------------\n\nOAuth 2.0 has short-lived tokens and long-lived tokens. For one-off operations, short-lived [access tokens](https://tools.ietf.org/html/rfc6749#section-1.4) are the best option. These tokens expire shortly after they are granted. For long running jobs, you may want to look into acquiring a [refresh token](https://developers.google.com/youtube/v3/guides/authentication#OAuth2_Refreshing_a_Token), which is used to fetch short-lived access tokens.\n\nTo ensure that your application receives a long-lived refresh token and not a short-lived access token, use the \"Installed Application\" flow when creating a client ID, and select `Other` for the \"Installed application type\" value:\n\nIt's recommended that you use the \"Installed application\" flow for this use case. If you need long-lived access to the YouTube API in a web application, you can retrieve one by setting the `access_type` parameter to `offline` and the `approval_prompt` parameter to `force` in the [initial authorization request or your client configuration](https://developers.google.com/accounts/docs/OAuth2WebServer#offline). Some client libraries will manage fetching and refreshing access tokens. If you are interested in writing your own custom authorization code, we published a [blog post on the Google Code blog](http://googlecode.blogspot.com/2011/10/upcoming-changes-to-oauth-20-endpoint.html) that you can use as the basis for your code.\n\nUsing OAuth 2.0 with phones, tablets and other devices\n------------------------------------------------------\n\nWhen writing Android applications, developers can take advantage of [Google Play services](http://developer.android.com/google/play-services/index.html) to handle the authorization details. Google Play services offers a [standard authorization flow for all Google APIs](http://developer.android.com/google/play-services/auth.html), including APIs for the YouTube platform. This approach will provide a far superior user experience for users of your Android application than a custom authentication using ClientLogin.\n\nOn iOS devices, Google provides two options:\n\n\n- the [Google+ Platform for iOS](https://developers.google.com/+/mobile/ios/), which integrates sign-in for Google products and also enables social features\n- the [gtm-oauth2 toolkit](https://github.com/google/gtm-oauth2), which provides an authorization UIWebView and manages tokens\n\n\u003cbr /\u003e\n\nFor devices that are meant to act as \"second screen\" devices or devices such as televisions without easy-to-use input mechanisms, [OAuth 2.0 for Devices](https://developers.google.com/accounts/docs/OAuth2ForDevices) is the preferred approach. OAuth 2.0 for Devices works by presenting a unique code for a user when an authorization request is required. At this point, users are asked to browse to \u003chttp://google.com/device\u003e on another device, such as a laptop or a phone, and enter in the unique code. The application presents a screen that looks something like this:\n\nWhile the user is entering the code on another device, the application periodically polls to see if the code has been entered. Once it has, it retrieves a token for making API calls. To see this in action, check out [the demo](http://stb-web-app.appspot.com/static/index.html), which can be run on any web-enabled device. The API itself is platform-agnostic, making it useful for devices that don't have web rendering capabilities. We've posted [sample code in Python](https://code.google.com/p/gdata-samples/source/browse/trunk/ytplayer/stb-web-app/?r=238) for the demo to be used as a reference.\n\nSummary\n-------\n\nOAuth 2.0 authorization provides flexibility for developers that require YouTube authorization. Developers familiar with ClientLogin may find that setting up their applications to use OAuth 2.0 requires slightly more work to get started, but once ported, OAuth 2.0 applications offer more flexibility, security and usability across multiple platforms for end users.\n\nIf you have any more questions about OAuth 2.0 or any of the examples in this article, please feel feel to ask with the [youtube-api tag on StackOverflow](http://stackoverflow.com/questions/tagged/youtube-api)."]]