Using YouTube v3 Data API for .NET, how can I get the refresh token?
I need to be able to use a refresh token to be able to re-authenticate the token after the access token has expired. How can I do this using the C # v3 API? I looked at the UserCredential class and the AuthorizationCodeFlow class and nothing jumps out at me.
I am using the following code for its initial authentication.
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
AuthorizeAsync(CancellationToken.None);
if (result.Credential != null)
{
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "YouTube Upload Tool"
});
}
And this is my AppFlowMetadata strong> class .
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "ID",
ClientSecret = "SECRET",
},
Scopes = new[] { YouTubeService.Scope.YoutubeUpload },
DataStore = new EFDataStore(-1) // A data store I implemented using Entity Framework 6.
});
public override string GetUserId(Controller controller)
{
return "test";
}
public override IAuthorizationCodeFlow Flow
{
get { return flow; }
}
}
If anyone can suggest anything, I would really appreciate it. Thank.
source to share
Until this is an answer, so I got around it. I had to create a GET request for authorization (redirect the user to the returned url and set up a Controller action to receive the callback specified in your google developer console) and a PUT request for the Token (which I then saved with EF6) manually. I used System.Net.Http.HttpClient
to execute these queries, which was pretty simple. See this link for all the details I need in order for this to work.
This was the only way to install it access_type
offline. If the .NET API does this, I'm still curious about how to do it.
With the token data saved, I now use the API to validate and update the token when I need it. I actually did this in a server side application, not an MVC application (hence EF token persistence).
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "ID",
ClientSecret = "Secret"
},
new[] { YouTubeService.Scope.YoutubeUpload },
"12345",
CancellationToken.None,
new EFDataStore(-1) // My own implementation of IDataStore
);
// This bit checks if the token is out of date,
// and refreshes the access token using the refresh token.
if(credential.Token.IsExpired(SystemClock.Default))
{
if (!await credential.RefreshTokenAsync(CancellationToken.None))
{
Console.WriteLine("No valid refresh token.");
}
}
var service = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MY App"
});
I hope this helps others.
source to share