示例#1
0
        private void VerifyAndRefreshCredentials(TransientCredentials tc)
        {
            var userCredential = tc.Token as UserCredential;
            var token          = userCredential?.Token;

            if (IsValidToken(token))
            {
                // We already have a valid OAuth token.
                return;
            }

            if (userCredential == null)
            {
                // Attempt to load a cached OAuth token.
                var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecretsStream = ClientSecretsStream,
                    DataStore           = GetCredentialsDataStoreForBlog(tc.Username),
                    Scopes = GoogleAPIScopes,
                });

                var loadTokenTask = flow.LoadTokenAsync(tc.Username, CancellationToken.None);
                loadTokenTask.Wait();
                if (loadTokenTask.IsCompleted)
                {
                    // We were able re-create the user credentials from the cache.
                    userCredential = new UserCredential(flow, tc.Username, loadTokenTask.Result);
                    token          = loadTokenTask.Result;
                }
            }

            if (!IsValidToken(token))
            {
                // The token is invalid, so we need to login again. This likely includes popping out a new browser window.
                if (BlogClientUIContext.SilentModeForCurrentThread)
                {
                    // If we're in silent mode where prompting isn't allowed, throw the verification exception
                    throw new BlogClientAuthenticationException(String.Empty, String.Empty);
                }

                // Start an OAuth flow to renew the credentials.
                var authorizationTask = GetOAuth2AuthorizationAsync(tc.Username, CancellationToken.None);
                authorizationTask.Wait();
                if (authorizationTask.IsCompleted)
                {
                    userCredential = authorizationTask.Result;
                    token          = userCredential?.Token;
                }
            }

            if (!IsValidToken(token))
            {
                // The token is still invalid after all of our attempts to refresh it. The user did not complete the
                // authorization flow, so we interpret that as a cancellation.
                throw new BlogClientOperationCancelledException();
            }

            // Stash the valid user credentials.
            tc.Token = userCredential;
        }
示例#2
0
        public async Task <UserCredential> LoadUserCredentialsAsync()
        {
            ClaimsPrincipal user = httpContextAccessor.HttpContext.User;

            string key = user.FindFirstValue(AdditionalClaimTypes.TokenResponseKey);

            if (key == null)
            {
                throw new Exception("An [Authorize] annotation is missing from this endpoint.");
            }

            TokenResponse token = await flow.LoadTokenAsync(key, CancellationToken.None);

            return(new UserCredential(flow, key, token));
        }
示例#3
0
        async Task get_google_credential()
        {
            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecretsStream = stream,
                    Scopes    = new[] { DriveService.Scope.DriveReadonly },
                    DataStore = new FileDataStore("oauth/drive")
                });

                TokenResponse token = await flow.LoadTokenAsync(Environment.UserName, CancellationToken.None);

                if (token == null)
                {
                    return;
                }

                credential = new UserCredential(flow, Environment.UserName, token);

                //bool res = await credential.RevokeTokenAsync(CancellationToken.None);
            }

            // Create Drive API service.
            driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = this.GetType().ToString(),
            });

            var req = driveService.About.Get();

            req.Fields = "user(displayName,photoLink, me, emailAddress), storageQuota(limit,usage), maxImportSizes, maxUploadSize";
            try
            {
                About ab = await req.ExecuteAsync();

                lbUserinfo.Text      = $"{ab.User.DisplayName} - {ab.User.EmailAddress}";
                lbStorageamount.Text = $"{ab.StorageQuota.Usage.ToReadableSize()}/{ab.StorageQuota.Limit.ToReadableSize()}";
            }
            catch (TokenResponseException ex)
            {
                credential   = null;
                driveService = null;
                btnClearLocal.PerformClick();
            }
        }
 private UserCredential GetCredentials(string userEmailAddress)
 {
     if (_credentials == null)
     {
         var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer {
             ClientSecrets = GetClientSerects(),
             Scopes        = _scopes
         });
         var token = flow.LoadTokenAsync(userEmailAddress, CancellationToken.None).Result;
         _credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
             GetClientSerects(),
             _scopes,
             userEmailAddress,
             CancellationToken.None,
             new FileDataStore("Daimto.GoogleCalendar.Auth.Store")).Result;
     }
     return(_credentials);
 }
示例#5
0
        private static async Task <UserCredential> GetCredential(long userId, ILifetimeScope child, CancellationToken cancellationToken)
        {
            var initializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = GetGoogleClientSecrets().Secrets,
                Scopes        = new[] { CalendarService.Scope.CalendarReadonly },
                DataStore     = child.Resolve <GoogleDataStore>()
            };
            //TODO: need to find solution We can't dispose the flow because we are using it in the code
            var flow = new GoogleAuthorizationCodeFlow(initializer);

            var gToken = await flow.LoadTokenAsync(userId.ToString(), cancellationToken);

            if (gToken == null)
            {
                throw new NotFoundException(nameof(gToken));
            }
            var credential = new UserCredential(flow, userId.ToString(), gToken);

            return(credential);
        }
示例#6
0
        /// <summary>
        /// 로그인 처리 코드를 가져와 토큰으로 교환
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="taskCancellationToken"></param>
        /// <returns></returns>
        public async Task <UserCredential> AuthorizeAsync(string userId, CancellationToken taskCancellationToken)
        {
            // 토큰이 로컬에 저장되어 있으면 저장되어있는 토큰을 불러옴
            var token = await flow.LoadTokenAsync(userId, taskCancellationToken).ConfigureAwait(false);

            // 로컬에 저장되어 있는 토큰이 없으면 실행
            if (token == null || (token.RefreshToken == null && token.IsExpired(flow.Clock)))
            {
                var authorizationCode = await loginform.GetAuthenticationToken(flow.ClientSecrets.ClientId, flow.Scopes, userId, GoogleAuthConsts.AuthorizationUrl, GoogleAuthConsts.InstalledAppRedirectUri, LoginOption.GoogleDrive);

                if (string.IsNullOrEmpty(authorizationCode))
                {
                    return(null);
                }
                //Logger.Debug("Received \"{0}\" code", response.Code);

                // 코드를 기반으로 토큰을 얻어옴
                token = await flow.ExchangeCodeForTokenAsync(userId, authorizationCode, GoogleAuthConsts.InstalledAppRedirectUri,
                                                             taskCancellationToken).ConfigureAwait(false);
            }

            return(new UserCredential(flow, userId, token));
        }
示例#7
0
        public async Task <UserCredential> LoadUserCredentialsAsync(string key)
        {
            TokenResponse token = await _flow.LoadTokenAsync(key, CancellationToken.None) ?? throw new FileLoadException("Failed to load the user's Google access token from the data store.");

            return(new UserCredential(_flow, key, token));
        }