Rafraichir le token

This commit is contained in:
2017-07-18 11:02:37 +02:00
parent 6895c19238
commit a1c965ed3a
2 changed files with 31 additions and 0 deletions

View File

@ -36,6 +36,8 @@ namespace Yavsc.Services
{
using System.Threading;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Util;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Calendar;
@ -240,6 +242,10 @@ namespace Yavsc.Services
var login = await _dbContext.GetGoogleUserLoginAsync(userId);
if (login == null) return null;
var token = await _flow.LoadTokenAsync(login.ProviderKey, CancellationToken.None);
var c = SystemClock.Default;
if (token.IsExpired(c)) {
token = await RefreshToken(token);
}
UserCredential cred = new UserCredential(_flow,login.ProviderKey,token);
return new CalendarService(new BaseClientService.Initializer()
{
@ -247,5 +253,23 @@ namespace Yavsc.Services
ApplicationName = "Yavsc"
});
}
public static async Task<TokenResponse> RefreshToken(TokenResponse oldResponse)
{
string ep = " https://www.googleapis.com/oauth2/v4/token";
// refresh_token client_id client_secret grant_type=refresh_token
try {
using (var m = new SimpleJsonPostMethod(ep)) {
return await m.Invoke<TokenResponse>(
new { refresh_token= oldResponse.RefreshToken, client_id=Startup.GoogleSettings.ClientId,
client_secret=Startup.GoogleSettings.ClientSecret,
grant_type="refresh_token" }
);
}
}
catch (Exception ex) {
throw new Exception ("Quelque chose s'est mal passé à l'envoi",ex);
}
}
}
}