public bool AddCredential(string credentialType, string accessToken, DateTime? expires, string renewalToken = null) { bool exists = false; UserCredential credential; // TODO: encrypt token if (this.UserCredentials.Any(uc => uc.CredentialType == credentialType)) { // update existing token credential = this.UserCredentials.Single<UserCredential>(uc => uc.CredentialType == credentialType); exists = true; } else { // add new token credential = new UserCredential() { UserID = this.ID, CredentialType = credentialType, }; this.UserCredentials.Add(credential); } credential.AccessToken = accessToken; credential.AccessTokenExpiration = expires; if (renewalToken != null) { credential.RenewalToken = renewalToken; } credential.LastModified = DateTime.UtcNow; return exists; }
UserCredential RenewAccessToken(UserCredential googleConsent) { string format = "client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token"; string formParams = string.Format(format, Uri.EscapeDataString(GoogleClient.ID), Uri.EscapeDataString(GoogleClient.Secret), Uri.EscapeDataString(googleConsent.RenewalToken)); byte[] byteArray = Encoding.ASCII.GetBytes(formParams); const string googleOAuth2TokenServiceUrl = "https://accounts.google.com/o/oauth2/token"; WebRequest request = WebRequest.Create(googleOAuth2TokenServiceUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream outStream = request.GetRequestStream(); outStream.Write(byteArray, 0, byteArray.Length); outStream.Close(); try { WebResponse response = request.GetResponse(); HttpStatusCode responseStatus = ((HttpWebResponse)response).StatusCode; Stream inStream = response.GetResponseStream(); StreamReader reader = new StreamReader(inStream); string jsonToken = reader.ReadToEnd(); JsonGoogleToken token = JsonSerializer.Deserialize<JsonGoogleToken>(jsonToken); googleConsent.AccessToken = token.access_token; googleConsent.AccessTokenExpiration = DateTime.UtcNow.AddSeconds(token.expires_in); storage.SaveChanges(); reader.Close(); inStream.Close(); response.Close(); } catch (Exception e) { TraceLog.TraceException("Could not refresh Google access token", e); } return googleConsent; }