我使用以下代码获取授权并上传到YouTube:
我已经从谷歌请求了我的令牌并且用户已经登录并且我已经获得了我的授权令牌。
我已使用以下内容将此交换为刷新和访问令牌:
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues("https://accounts.google.com/o/oauth2/token", new NameValueCollection()
{
{"code", Session["authCode"].ToString()},
{"redirect_uri", "http://YouTubeTest.org/testpage.aspx"},
{
"client_id", clientID
},
{"client_secret", secret},
{"grant_type", "authorization_code"}
});
string result =Encoding.UTF8.GetString(response);
XElement node = XElement.Parse(JsonConvert.DeserializeXNode(result, "Root").ToString());
Session["refreshtoken"] = node.Element("refresh_token").Value;
}
然后存储这些细节。
当用户点击上传视频时,我按如下方式初始化youtube服务:
ClientSecrets secrets = new ClientSecrets()
{
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET
};
var token = new TokenResponse { RefreshToken = REFRESH_TOKEN };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}),
"user",
token);
var service = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "TestProject"
});
此时我想知道我发送的刷新令牌是否有效,但似乎没有任何说法。
我似乎知道的唯一方法是通过执行以下操作实际尝试上传视频:
public String UploadVideo(Stream stream, String title, String desc, String[] tags, String categoryId, Boolean isPublic)
{
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = title;
video.Snippet.Description = desc;
video.Snippet.Tags = tags;
video.Snippet.CategoryId = categoryId; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = isPublic ? "public" : "private";
var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", stream, "video/*");
videosInsertRequest.ProgressChanged += insertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += insertRequest_ResponseReceived;
videosInsertRequest.Upload();
return UploadedVideoId;
}
void insertRequest_ResponseReceived(Video video)
{
UploadedVideoId = video.Id;
}
void insertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
// You can handle several status messages here.
switch (progress.Status)
{
case UploadStatus.Failed:
UploadedVideoId = "FAILED";
^^如果此时令牌无效,则进度有一个例外" Invalid_grant"
break;
case UploadStatus.Completed:
break;
default:
break;
}
}
如果我的刷新令牌有效,我如何在尝试上传之前找到答案?
此时很难从中恢复,所以理想情况下,我希望能够在初始化youtube服务时或之后检查它。
答案 0 :(得分:0)
验证令牌是Google Identity文档的一部分。它建议您可以通过在Web服务端点中请求来验证令牌。
您可以将https://www.googleapis.com/oauth2/v3/tokeninfo
与access_token
作为参数
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg
响应将具有描述令牌或错误的JSON对象。有关这方面的更多详细信息,请参阅上述文档中的参考页面。