使用预先存在的访问令牌通过 ASP.NET 创建 YouTube 服务

2024-01-05

我一直在开发一个网站,供用户将视频上传到共享的 YouTube 帐户以供以后访问。经过大量工作,我已经能够获得活动令牌和可行的刷新令牌。

然而,初始化的代码YouTubeService对象看起来像这样:

UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets, 
        // This OAuth 2.0 access scope allows an application to upload files to the
        // authenticated user's YouTube channel, but doesn't allow other types of access.
        new[] { YouTubeService.Scope.YoutubeUpload },
        "user",
        CancellationToken.None
    );
}

var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = Assembly.GetExecutingAssembly().GetName().Name,
});

我已经有了一个令牌,我想使用我的。我正在使用 ASP.NET 版本 3.5,所以我无法执行async无论如何打电话。

有什么办法我可以创建一个YouTubeService没有对象的async调用,并使用我自己的令牌?有没有办法可以在没有授权代理的情况下构建凭证对象?

或者,该应用程序使用 YouTube API V2 相当长一段时间,并且有一个采用令牌的表单,并对与 API V2 中的令牌一起生成的 YouTube URI 执行后操作。有没有办法可以用 V3 来实现?有没有一种方法可以使用 Javascript 上传视频,并且可能有一个我可以在代码中使用的示例?


注意:我最终将框架升级到 4.5 以访问 google 库。

要以编程方式初始化 UserCredential 对象,您必须构建 Flow 和 TokenResponse。流程需要一个范围(也就是我们为凭证寻求的权限)。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Auth.OAuth2.Flows;

string[] scopes = new string[] {
    YouTubeService.Scope.Youtube,
    YouTubeService.Scope.YoutubeUpload
};

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
    ClientSecrets = new ClientSecrets
    {
        ClientId = XXXXXXXXXX,  <- Put your own values here
        ClientSecret = XXXXXXXXXX  <- Put your own values here
    },
    Scopes = scopes,
    DataStore = new FileDataStore("Store")
});

TokenResponse token = new TokenResponse {
    AccessToken = lblActiveToken.Text,
    RefreshToken = lblRefreshToken.Text
};

UserCredential credential = new UserCredential(flow, Environment.UserName, token);

希望有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用预先存在的访问令牌通过 ASP.NET 创建 YouTube 服务 的相关文章

随机推荐