public YouTubeService NewTestYouTubeService(string accessToken, string refreshToken)
        {
            var access_token = accessToken;
            var refresh_token = refreshToken;

            TokenResponse token = new TokenResponse
            {
                AccessToken = access_token,
                RefreshToken = refresh_token
            };

            var cred = new UserCredential
                (new GoogleAuthorizationCodeFlow(
                    new GoogleAuthorizationCodeFlow.Initializer()
                    {
                        ClientSecrets = new ClientSecrets()
                        {
                            ClientId = "//clientId",
                            ClientSecret = "//clientSecret"
                        }
                    }
                    ),
                    "testUser1",
                    token
                );

            return new YouTubeService(new BaseClientService.Initializer()
            {
                ApplicationName = this.GetType().ToString(),
                HttpClientInitializer = cred
            });
        }
        public void IsExpired_True()
        {
            var issued = DateTime.Now;
            var newNow = DateTime.Now.AddSeconds(200);

            var mockClock = new MockClock()
            {
                Now = newNow
            };

            // Issued not set.
            var response = new TokenResponse();
            Assert.True(response.IsExpired(mockClock));

            // ExpiresInSeconds is not set.
            response = new TokenResponse() { Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { ExpiresInSeconds = 1, Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { ExpiresInSeconds = 100, Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { ExpiresInSeconds = 140, Issued = issued };
            Assert.True(response.IsExpired(mockClock));
        }
示例#3
0
        private DriveService CreateServie()
        { 
                var tokenResponse = new TokenResponse
                {
                    AccessToken = WebStorageConstants.GoogleDriveAccessToken,
                    RefreshToken = WebStorageConstants.GoogleRefreshToken,
                };

                var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = WebStorageConstants.GoogleDriveId,
                        ClientSecret = WebStorageConstants.GoogleDriveSecret
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore(WebStorageConstants.GoogleDriveApplicationName)
                });

                var credential = new UserCredential(apiCodeFlow, WebStorageConstants.GoogleDriveEmail, tokenResponse);

                var newService = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = WebStorageConstants.GoogleDriveApplicationName
                });

                return newService;
        }
 public void TestConstructor()
 {
     var response = new TokenResponse();
     Assert.Null(response.AccessToken);
     Assert.Null(response.ExpiresInSeconds);
     Assert.Null(response.RefreshToken);
     Assert.Null(response.Scope);
     Assert.AreEqual(DateTime.MinValue, response.Issued);
 }
示例#5
0
    public static AuthorizationCodeWebApp.AuthResult checkExpiration(Controller controller, AuthorizationCodeWebApp.AuthResult authorization)
    {
        if (authorization.Credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default))
        {
            Google.Apis.Auth.OAuth2.Responses.TokenResponse token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse();
            //recreate the token
            token = authorization.Credential.Flow.RefreshTokenAsync(
                UserAccountsController.getUserId(controller.Session).ToString(),
                authorization.Credential.Token.RefreshToken,
                CancellationToken.None
                ).Result;

            authorization = getAuthorization(controller);
        }
        return(authorization);
    }
        private void EnsureService()
        {
            if (!_setting.UseGoogleDrive)
            {
                return;
            }

            if (_driveService != null)
            {
                return;
            }

            if (string.IsNullOrEmpty(_setting.GoogleClientId) || string.IsNullOrEmpty(_setting.GoogleClientSecret) ||
                 string.IsNullOrEmpty(_setting.GoogleRefreshToken))
            {
                throw new ApplicationException("Missing google drive configuration");
            }

            try
            {
                var initializer = new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = _setting.GoogleClientId,
                        ClientSecret = _setting.GoogleClientSecret
                    }
                };
                var flow = new AuthorizationCodeFlow(initializer);
                //flow.RefreshTokenAsync("user", Configuration.GoogleRefreshToken, new CancellationTokenSource().Token);

                var tokenResponse = new TokenResponse { RefreshToken = _setting.GoogleRefreshToken };
                var userCredential = new UserCredential(flow, _setting.GoogleLocalUserId, tokenResponse);

                _driveService = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = userCredential,
                    ApplicationName = "Jarboo.Admin"
                });
            }
            catch (Exception ex)
            {
                _driveService = null;

                throw;
            }
        }
示例#7
0
        public static async Task<DriveService> GetClient(TokenResponse token)
        {
            var credentials = new UserCredential(
               AuthFlow,
               null,
               token);

            var driveInitializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                HttpClientFactory = new GoogleDriveHttpClientFactory(),
                ApplicationName = "KeeAnywhere",
            };

            var client = new DriveService(driveInitializer);

            return client;
        }
        public void IsExpired()
        {
            var issued = DateTime.Now;
            var newNow = DateTime.Now.AddSeconds(100);

            var mockClock = new MockClock
            {
                Now = newNow
            };

            // Issued not set.
            var response = new TokenResponse();
            Assert.True(response.IsExpired(mockClock));

            // ExpiresInSeconds is not set.
            response = new TokenResponse() { Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 1, Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 100, Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 158, Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 159, Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 160, Issued = issued };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 161, Issued = issued };
            Assert.False(response.IsExpired(mockClock));

            response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 162, Issued = issued };
            Assert.False(response.IsExpired(mockClock));
        }
        public async Task<bool> Claim(Uri uri, string documentTitle)
        {
            var parts = documentTitle.Split(' ');

            if (parts.Length < 1 || parts[0] != "Success")
                return false;

            var code = parts[1].Split('=')[1];

            try
            {
                _token =
                    await
                        GoogleDriveHelper.AuthFlow.ExchangeCodeForTokenAsync(null, code, GoogleDriveHelper.RedirectUri,
                            CancellationToken.None).ConfigureAwait(false);
                return _token != null;
            }
            catch (TokenResponseException)
            {
                return false;
            }
        }
        private async Task StoreAuthToken(string userId, string userName, string refreshToken, string accessToken, long expiresIn)
        {
            var flow  = GmailApiComponent.CreateFlow(userId);
            var token = await flow.DataStore.GetAsync <TokenResponse>(userName);

            if (token == null && string.IsNullOrEmpty(refreshToken))
            {
                throw new HttpException((int)System.Net.HttpStatusCode.Unauthorized, "No refresh token provided.");
            }

            if (token == null)
            {
                token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse
                {
                    RefreshToken = refreshToken
                };
            }
            token.AccessToken      = accessToken;
            token.ExpiresInSeconds = expiresIn;
            token.Issued           = flow.Clock.UtcNow;

            await flow.DataStore.StoreAsync(userName, token);
        }
        /// <summary>
        /// Asynchronously parses a <see cref="TokenResponse"/> instance from the specified <see cref="HttpResponseMessage"/>.
        /// </summary>
        /// <param name="response">The http response from which to parse the token.</param>
        /// <param name="clock">The clock used to set the <see cref="Issued"/> value of the token.</param>
        /// <param name="logger">The logger used to output messages incase of error.</param>
        /// <exception cref="TokenResponseException">
        /// The response was not successful or there is an error parsing the response into valid <see cref="TokenResponse"/> instance.
        /// </exception>
        /// <returns>
        /// A task containing the <see cref="TokenResponse"/> parsed form the response message.
        /// </returns>
        public static async Task <TokenResponse> FromHttpResponseAsync(HttpResponseMessage response, IClock clock, ILogger logger)
        {
            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var typeName = "";

            try
            {
                if (!response.IsSuccessStatusCode)
                {
                    typeName = nameof(TokenErrorResponse);
                    var error = NewtonsoftJsonSerializer.Instance.Deserialize <TokenErrorResponse>(content);
                    throw new TokenResponseException(error, response.StatusCode);
                }

                TokenResponse newToken;
                // GCE's metadata server identity endpoint doesn't return a TokenResponse but the raw
                // id_token, so we build a TokenResponse from that.
                if (response.RequestMessage?.RequestUri?.AbsoluteUri.StartsWith(GoogleAuthConsts.EffectiveComputeOidcTokenUrl) == true)
                {
                    newToken = new TokenResponse
                    {
                        IdToken = content
                    };
                }
                else
                {
                    typeName = nameof(TokenResponse);
                    newToken = NewtonsoftJsonSerializer.Instance.Deserialize <TokenResponse>(content);
                }
                // We make some modifications to the token before returning, to guarantee consistency
                // for our code across endpoint usage.

                // We should set issuance ourselves.
                newToken.IssuedUtc = clock.UtcNow;
                // If no access token was specified, then we're probably receiving
                // and OIDC token for IAP. The IdToken is used for access in that case.
                newToken.AccessToken ??= newToken.IdToken;

                // If no expiry is specified, maybe the IdToken has it specified.
                // We can try and get it from there.
                if (newToken.ExpiresInSeconds is null && newToken.IdToken != null)
                {
                    // Unpack the IdToken.
                    var idToken = SignedToken <JsonWebSignature.Header, JsonWebSignature.Payload> .FromSignedToken(newToken.IdToken);

                    // If no expiry was specified in the ID token, there's nothing we can do.
                    if (idToken.Payload.ExpirationTimeSeconds.HasValue)
                    {
                        var expiration = UnixEpoch.AddSeconds(idToken.Payload.ExpirationTimeSeconds.Value);
                        newToken.ExpiresInSeconds = (long)(expiration - newToken.IssuedUtc).TotalSeconds;
                    }
                }
                return(newToken);
            }
            catch (Newtonsoft.Json.JsonException ex)
            {
                logger.Error(ex, $"Exception was caught when deserializing {typeName}. Content is: {content}");
                throw new TokenResponseException(new TokenErrorResponse
                {
                    Error = "Server response does not contain a JSON object. Status code is: " + response.StatusCode
                }, response.StatusCode);
            }
        }
 /// <summary>Constructs a new credential instance.</summary>
 /// <param name="flow">Authorization code flow.</param>
 /// <param name="userId">User identifier.</param>
 /// <param name="token">An initial token for the user.</param>
 public UserCredential(IAuthorizationCodeFlow flow, string userId, TokenResponse token)
 {
     this.flow = flow;
     this.userId = userId;
     this.token = token;
 }
 /// <summary>Verifies that the token response contains the expected data.</summary>
 /// <param name="response">The token response</param>
 private void SubtestTokenResponse(TokenResponse response)
 {
     Assert.That(response.RefreshToken, Is.EqualTo("r"));
     Assert.That(response.ExpiresInSeconds, Is.EqualTo(100));
     Assert.That(response.Scope, Is.EqualTo("b"));
 }
        /// <summary>
        /// Processes the request based on the path.
        /// </summary>
        /// <param name="context">Contains the request and response.</param>
        public void ProcessRequest(HttpContext context)
        {
            // Redirect base path to signin.
            if (context.Request.Path.EndsWith("/"))
            {
                context.Response.RedirectPermanent("signin.ashx");
            }

            // This is reached when the root document is passed. Return HTML
            // using index.html as a template.
            if (context.Request.Path.EndsWith("/signin.ashx"))
            {
                String state = (String)context.Session["state"];

                // Store a random string in the session for verifying
                // the responses in our OAuth2 flow.
                if (state == null)
                {
                    Random random = new Random((int)DateTime.Now.Ticks);
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < 13; i++)
                    {
                        builder.Append(Convert.ToChar(
                                Convert.ToInt32(Math.Floor(
                                        26 * random.NextDouble() + 65))));
                    }
                    state = builder.ToString();
                    context.Session["state"] = state;
                }

                // Render the templated HTML.
                String templatedHTML = File.ReadAllText(
                     context.Server.MapPath("index.html"));
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME);
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId);
                templatedHTML = Regex.Replace(templatedHTML,
                    "[{]{2}\\s*STATE\\s*[}]{2}", state);

                context.Response.ContentType = "text/html";
                context.Response.Write(templatedHTML);
                return;
            }

            if (context.Session["authState"] == null)
            {
                // The connect action exchanges a code from the sign-in button,
                // verifies it, and creates OAuth2 credentials.
                if (context.Request.Path.Contains("/connect"))
                {
                    // Get the code from the request POST body.
                    StreamReader sr = new StreamReader(
                        context.Request.InputStream);
                    string code = sr.ReadToEnd();

                    string state = context.Request["state"];

                    // Test that the request state matches the session state.
                    if (!state.Equals(context.Session["state"]))
                    {
                        context.Response.StatusCode = 401;
                        return;
                    }

                    // Use the code exchange flow to get an access and refresh token.
                    IAuthorizationCodeFlow flow =
                        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                        {
                            ClientSecrets = secrets,
                            Scopes = SCOPES
                        });

                    token = flow.ExchangeCodeForTokenAsync("", code, "postmessage",
                            CancellationToken.None).Result;

                    // Create an authorization state from the returned token.
                    context.Session["authState"] = token;

                    // Get tokeninfo for the access token if you want to verify.
                    Oauth2Service service = new Oauth2Service(
                        new Google.Apis.Services.BaseClientService.Initializer());
                    Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
                    request.AccessToken = token.AccessToken;

                    Tokeninfo info = request.Execute();

                    string gplus_id = info.UserId;
                }
                else
                {
                    // No cached state and we are not connecting.
                    context.Response.StatusCode = 400;
                    return;
                }
            }
            else if (context.Request.Path.Contains("/connect"))
            {
                // The user is already connected and credentials are cached.
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = 200;
                context.Response.Write(JsonConvert.SerializeObject("Current user is already connected."));
                return;
            }
            else
            {
                // Register the authenticator and construct the Plus service
                // for performing API calls on behalf of the user.
                token = (TokenResponse)context.Session["authState"];
                IAuthorizationCodeFlow flow =
                    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                    {
                        ClientSecrets = secrets,
                        Scopes = SCOPES
                    });

                UserCredential credential = new UserCredential(flow, "me", token);
                bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;

                token = credential.Token;
                ps = new PlusService(
                    new Google.Apis.Services.BaseClientService.Initializer()
                    {
                        ApplicationName = ".NET Quickstart",
                        HttpClientInitializer = credential
                    });
            }

            // Perform an authenticated API request to retrieve the list of
            // people that the user has made visible to the app.
            if (context.Request.Path.Contains("/people"))
            {
                // Get the PeopleFeed for the currently authenticated user.
                PeopleFeed pf = ps.People.List("me",
                        PeopleResource.ListRequest.CollectionEnum.Visible).Execute();

                // This JSON, representing the people feed, will later be
                // parsed by the JavaScript client.
                string jsonContent =
                    Newtonsoft.Json.JsonConvert.SerializeObject(pf);
                context.Response.ContentType = "application/json";
                context.Response.Write(jsonContent);
                return;
            }

            // Disconnect the user from the application by revoking the tokens
            // and removing all locally stored data associated with the user.
            if (context.Request.Path.Contains("/disconnect"))
            {
                // Perform a get request to the token endpoint to revoke the
                // refresh token.
                token = (TokenResponse)context.Session["authState"];
                string tokenToRevoke = (token.RefreshToken != null) ?
                    token.RefreshToken : token.AccessToken;

                WebRequest request = WebRequest.Create(
                    "https://accounts.google.com/o/oauth2/revoke?token=" +
                    tokenToRevoke);

                WebResponse response = request.GetResponse();

                // Remove the cached credentials.
                context.Session["authState"] = null;

                // You could reset the state in the session but you must also
                // reset the state on the client.
                // context.Session["state"] = null;
                context.Response.Write(
                    response.GetResponseStream().ToString().ToCharArray());
                return;
            }
        }
        // For more information on configuring authentication, please visit
        // http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request.
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enables the application to use a cookie to store information for the signed in user and to use a cookie
            // to temporarily store information about a user logging in with a third party login provider.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login
                    // to your account.  
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });            
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor
            // in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered
            // on the device where you logged in from. This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // ***
            // Enables logging in with the Google login provider.
            var google = new GoogleOAuth2AuthenticationOptions()
            {
                AccessType = "offline",     // Request a refresh token.
                ClientId = MyClientSecrets.ClientId,
                ClientSecret = MyClientSecrets.ClientSecret,
                Provider = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        var userId = context.Id;
                        context.Identity.AddClaim(new Claim(MyClaimTypes.GoogleUserId, userId));

                        var tokenResponse = new TokenResponse() {
                            AccessToken = context.AccessToken,
                            RefreshToken = context.RefreshToken,
                            ExpiresInSeconds = (long)context.ExpiresIn.Value.TotalSeconds,
                            Issued = DateTime.Now,
                        };

                        await dataStore.StoreAsync(userId, tokenResponse);
                    },
                },
            };

            foreach (var scope in MyRequestedScopes.Scopes)
            {
                google.Scope.Add(scope);
            }

            app.UseGoogleAuthentication(google);
        }
        public void LoadTokenAsync_TokenResponse()
        {
            TokenResponse response = new TokenResponse
            {
                AccessToken = "access"
            };

            TaskCompletionSource<TokenResponse> tcs = new TaskCompletionSource<TokenResponse>();
            tcs.SetResult(response);
            var result = SubtestLoadTokenAsync(tcs);
            Assert.That(result, Is.EqualTo(response));
        }
示例#17
0
        private YouTubeService BuildService()
        {
            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"
            });

            //service.HttpClient.Timeout = TimeSpan.FromSeconds(360); // Choose a timeout to your liking
            return service;
        }
        public void Open(OAuth20Token token)
        {
            if (IsOpened)
                return;

            if (token == null) throw new UnauthorizedAccessException("Cannot create GoogleDrive session with given token");
            if (token.IsExpired) token = OAuth20TokenHelper.RefreshToken(GoogleUrlToken, token);
            _token = token;

            var tokenResponse = new TokenResponse
                {
                    AccessToken = _token.AccessToken,
                    RefreshToken = _token.RefreshToken,
                    Issued = _token.Timestamp,
                    ExpiresInSeconds = _token.ExpiresIn,
                    TokenType = "Bearer"
                };

            var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                        {
                            ClientId = _token.ClientID,
                            ClientSecret = _token.ClientSecret
                        },
                    Scopes = new[] { DriveService.Scope.Drive }
                });

            _driveService = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = new UserCredential(apiCodeFlow, string.Empty, tokenResponse)
                });

            IsOpened = true;
        }
        /// <summary>
        /// Requests a new token as specified in 
        /// https://developers.google.com/accounts/docs/OAuth2ServiceAccount#makingrequest.
        /// </summary>
        /// <param name="taskCancellationToken">Cancellation token to cancel operation.</param>
        /// <returns><c>true</c> if a new token was received successfully.</returns>
        public async Task<bool> RequestAccessTokenAsync(CancellationToken taskCancellationToken)
        {
            string serializedHeader = CreateSerializedHeader();
            string serializedPayload = GetSerializedPayload();

            StringBuilder assertion = new StringBuilder();
            assertion.Append(UrlSafeBase64Encode(serializedHeader))
                .Append(".")
                .Append(UrlSafeBase64Encode(serializedPayload));

            // Sign the header and the payload.
            var signature = UrlSafeBase64Encode(key.SignData(Encoding.ASCII.GetBytes(assertion.ToString()), "SHA256"));
            assertion.Append(".").Append(signature);

            // Create the request.
            var request = new GoogleAssertionTokenRequest()
            {
                Assertion = assertion.ToString()
            };

            Logger.Debug("Request a new access token. Assertion data is: " + request.Assertion);

            var newToken = await request.ExecuteAsync(httpClient, tokenServerUrl, taskCancellationToken, Clock)
                .ConfigureAwait(false);
            Token = newToken;
            return true;
        }
        public void IsExpired()
        {
            var issued = DateTime.Now;
            var newNow = DateTime.Now.AddSeconds(100);

            var mockClock = new MockClock
            {
                Now = newNow
            };

            // Issued not set.
            var response = new TokenResponse();

            Assert.True(response.IsExpired(mockClock));

            // ExpiresInSeconds is not set.
            response = new TokenResponse()
            {
                Issued = issued
            };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse()
            {
                AccessToken = "a", ExpiresInSeconds = 1, Issued = issued
            };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse()
            {
                AccessToken = "a", ExpiresInSeconds = 100, Issued = issued
            };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse()
            {
                AccessToken = "a", ExpiresInSeconds = 158, Issued = issued
            };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse()
            {
                AccessToken = "a", ExpiresInSeconds = 159, Issued = issued
            };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse()
            {
                AccessToken = "a", ExpiresInSeconds = 160, Issued = issued
            };
            Assert.True(response.IsExpired(mockClock));

            response = new TokenResponse()
            {
                AccessToken = "a", ExpiresInSeconds = 161, Issued = issued
            };
            Assert.False(response.IsExpired(mockClock));

            response = new TokenResponse()
            {
                AccessToken = "a", ExpiresInSeconds = 162, Issued = issued
            };
            Assert.False(response.IsExpired(mockClock));
        }
示例#21
0
        private static UserCredential GetCredentialWithAccessToken(string refreshToken, string clientID, string clientSecret, string[] scopes)
        {
            TokenResponse token = new TokenResponse
            {
                RefreshToken = refreshToken
            };

            IAuthorizationCodeFlow flow = new AuthorizationCodeFlow(new AuthorizationCodeFlow.Initializer(Google.Apis.Auth.OAuth2.GoogleAuthConsts.AuthorizationUrl, Google.Apis.Auth.OAuth2.GoogleAuthConsts.TokenUrl)
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = clientID,
                    ClientSecret = clientSecret
                },
                Scopes = scopes
            });

            UserCredential credential = new UserCredential(flow, "me", token);
            try
            {
                bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;
            }
            catch
            {
                throw;
            }
            return credential;
        }
        public static DriveService CreateServie(string applicationName, string clientId, string clientSecret, string accessToken, string refreshToken)
        {
            var tokenResponse = new TokenResponse
            {
                AccessToken = accessToken,
                RefreshToken = refreshToken,
            };

            var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = clientId,
                    ClientSecret = clientSecret
                },
                Scopes = new[]
                {
                    DriveService.Scope.Drive, // view and manage your files and documents
                    DriveService.Scope.DriveAppdata, // view and manage its own configuration data
                    DriveService.Scope.DriveAppsReadonly, // view your drive apps
                    DriveService.Scope.DriveFile, // view and manage files created by this app
                    DriveService.Scope.DriveMetadataReadonly, // view metadata for files
                    DriveService.Scope.DriveReadonly, // view files and documents on your drive
                    DriveService.Scope.DriveScripts
                },
                DataStore = new FileDataStore(applicationName)
            });

            var credential = new UserCredential(apiCodeFlow, "*****@*****.**", tokenResponse);

            var service = new DriveService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = applicationName
            });

            return service;
        }
        public void IsExpired_False()
        {
            var issued = DateTime.Now;
            var newNow = DateTime.Now.AddSeconds(200);

            var mockClock = new MockClock()
            {
                Now = newNow
            };

            var response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 141, Issued = issued };
            Assert.False(response.IsExpired(mockClock));

            response = new TokenResponse() { AccessToken = "a", ExpiresInSeconds = 142, Issued = issued };
            Assert.False(response.IsExpired(mockClock));
        }
 /// <summary>
 /// Determines the need for retrieval of a new authorization code, based on the given token and the 
 /// authorization code flow.
 /// </summary>
 public bool ShouldRequestAuthorizationCode(TokenResponse token)
 {
     // TODO: This code should be shared between this class and AuthorizationCodeInstalledApp.
     // If the flow includes a parameter that requires a new token, if the stored token is null or it doesn't
     // have a refresh token and the access token is expired we need to retrieve a new authorization code.
     return Flow.ShouldForceTokenRetrieval() || token == null || (token.RefreshToken == null
         && token.IsExpired(flow.Clock));
 }
示例#25
0
        /// <summary>
        /// Refreshes the token by calling to
        /// <see cref="Google.Apis.Auth.OAuth2.Flows.IAuthorizationCodeFlow.RefreshTokenAsync"/>.
        /// Then it updates the <see cref="TokenResponse"/> with the new token instance.
        /// </summary>
        /// <param name="taskCancellationToken">Cancellation token to cancel an operation.</param>
        /// <returns><c>true</c> if the token was refreshed.</returns>
        public async Task<bool> RefreshTokenAsync(CancellationToken taskCancellationToken)
        {
            if (Token.RefreshToken == null)
            {
                Logger.Warning("Refresh token is null, can't refresh the token!");
                return false;
            }

            // It's possible that two concurrent calls will be made to refresh the token, in that case the last one 
            // will win.
            var newToken = await flow.RefreshTokenAsync(userId, Token.RefreshToken, taskCancellationToken)
                .ConfigureAwait(false);

            Logger.Info("Access token was refreshed successfully");

            if (newToken.RefreshToken == null)
            {
                newToken.RefreshToken = Token.RefreshToken;
            }

            Token = newToken;
            return true;
        }
		/// <summary>Creates a user credential from JSON data.</summary>
		private static UserCredential CreateUserCredentialFromJson(JsonCredentialParameters credentialParameters)
		{
			if (credentialParameters.Type != JsonCredentialParameters.AuthorizedUserCredentialType ||
				string.IsNullOrEmpty(credentialParameters.ClientId) ||
				string.IsNullOrEmpty(credentialParameters.ClientSecret))
			{
				throw new InvalidOperationException("JSON data does not represent a valid user credential.");
			}

			var token = new TokenResponse
			{
				RefreshToken = credentialParameters.RefreshToken
			};

			var initializer = new GoogleAuthorizationCodeFlow.Initializer
			{
				ClientSecrets = new ClientSecrets
				{
					ClientId = credentialParameters.ClientId,
					ClientSecret = credentialParameters.ClientSecret
				}
			};
			var flow = new GoogleAuthorizationCodeFlow(initializer);
			return new UserCredential(flow, "ApplicationDefaultCredentials", token);
		}
        private async Task StoreAuthToken(string userId, string userName, string refreshToken, string accessToken, long expiresIn)
        {
            var flow = GmailApiComponent.CreateFlow(userId);
            var token = await flow.DataStore.GetAsync<TokenResponse>(userName);
            if (token == null && string.IsNullOrEmpty(refreshToken))
                throw new HttpException((int)System.Net.HttpStatusCode.Unauthorized, "No refresh token provided.");

            if (token == null)
            {
                token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse
                {
                    RefreshToken = refreshToken
                };
            }
            token.AccessToken = accessToken;
            token.ExpiresInSeconds = expiresIn;
            token.Issued = flow.Clock.UtcNow;

            await flow.DataStore.StoreAsync(userName, token);
        }
 private bool IsValidToken(TokenResponse token)
 {
     // If the token is expired but we have a non-null RefreshToken, we can assume the token will be 
     // automatically refreshed when we query Google Blogger and is therefore valid.
     return token != null && (!token.IsExpired(SystemClock.Default) || token.RefreshToken != null);
 }
 /// <summary>Stores the token in the <see cref="DataStore"/>.</summary>
 /// <param name="userId">User identifier.</param>
 /// <param name="token">Token to store.</param>
 /// <param name="taskCancellationToken">Cancellation token to cancel operation.</param>
 private async Task StoreTokenAsync(string userId, TokenResponse token, CancellationToken taskCancellationToken)
 {
     taskCancellationToken.ThrowIfCancellationRequested();
     if (DataStore != null)
     {
         await DataStore.StoreAsync<TokenResponse>(userId, token).ConfigureAwait(false);
     }
 }
 /// <summary>
 /// Metoda wypełniająca wszystkie niezbędne dane do autoryzacji w usłudze Google Calendar.
 /// </summary>
 private bool SetUserCalendarAuthData()
 {
     Logs.WriteErrorLog("SetUserCalendarAuthData");
     Logs.WriteErrorLog("ClientCredentials.ClientId: " + ClientCredentials.ClientId.ToString() + "ClientCredentials.ClientSecret: " + ClientCredentials.ClientSecret);
     Flow = new GoogleAuthorizationCodeFlow(
         new GoogleAuthorizationCodeFlow.Initializer
         {
             ClientSecrets = new ClientSecrets()
             {
                 ClientId = ClientCredentials.ClientId,
                 ClientSecret = ClientCredentials.ClientSecret
             }
         });
     Logs.WriteErrorLog("UserIdInDatabase: ");
     Logs.WriteErrorLog(UserIdInDatabase.ToString());
     var tokenFromWs = GetTokenFromWebService.GetTokenFromDatabase(UserIdInDatabase).Result;
     if (tokenFromWs == null)
     {
         IsCalendarAuthorized = false;
         return false;
     }
     Token = new TokenResponse
     {
         RefreshToken = tokenFromWs
     };
     IsCalendarAuthorized = true;
     return true;
 }
        private DriveService CreateDriveService(GoogleCredentials googleCredentials)
        {
            var authorizationCodeFlowInitializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = googleCredentials.ClientId,
                    ClientSecret = googleCredentials.ClientSecret
                }
            };
            var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(authorizationCodeFlowInitializer);
            var token = new TokenResponse { RefreshToken = googleCredentials.RefreshToken };
            var credentials = new UserCredential(googleAuthorizationCodeFlow, "user", token);

            var initializer = new BaseClientService.Initializer
            {
                ApplicationName = "Emby",
                HttpClientInitializer = credentials
            };

            return new DriveService(initializer)
            {
                HttpClient = { Timeout = TimeSpan.FromHours(1) }
            };
        }