/// <summary> /// Asynchronously checks the authentication. /// </summary> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > CheckAuthenticationAsync() { if (m_result == null) { m_result = new SerializableAPIResult <SerializableAPICredentials>(); } try { if (!HasCredentialsStored) { return(m_result); } if (s_credential == null) { await GetCredentialsAsync().ConfigureAwait(false); } using (DriveService client = GetClient()) { AboutResource.GetRequest request = client.About.Get(); request.Fields = "user"; await request.ExecuteAsync().ConfigureAwait(false); } } catch (GoogleApiException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; if (HasCredentialsStored) { await ResetSettingsAsync().ConfigureAwait(false); } } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(m_result); }
static AutoResetEvent AuthCompletedHandle; // перед запуском аутентификации нужно = new AutoResetEvent(false); // Параметры аутентификации платформ-специфичны. Поэтому перед началом работы нужно вызвать этот метод в проекте конкретной платформы. public static void InitAuthParameters(string clientId, string redirectUrl, string appName, Action actionToStartAuth) { // Сохраним эти переменные на случай, если нужно будет перелогиниться, т.е. создать новый Auth, т.е. снова вызвать InitAuthParameters(). authActionToStart = actionToStartAuth; authClientId = clientId; authRedirectUrl = redirectUrl; authAppName = appName; Auth = new OAuth2Authenticator( clientId, string.Empty, "https://www.googleapis.com/auth/drive", new Uri("https://accounts.google.com/o/oauth2/auth"), new Uri(redirectUrl), new Uri("https://accounts.google.com/o/oauth2/token"), isUsingNativeUI: true); Auth.Completed += async(sender, e) => { //Debug.WriteLine("EVENT Auth.Completed()"); AuthenticatorCompletedEventArgs args = e as AuthenticatorCompletedEventArgs; if (args.IsAuthenticated) { GoogleAuthorizationCodeFlow googleFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer() { ClientSecrets = new ClientSecrets() { ClientId = clientId, ClientSecret = string.Empty, }, Scopes = new string[] { "https://www.googleapis.com/auth/drive" } }); var token = new TokenResponse { AccessToken = args.Account.Properties["access_token"], RefreshToken = args.Account.Properties["refresh_token"] }; var credential = new UserCredential(googleFlow, "user", token); Service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = authAppName, }); //Получим справочную информацию об аккаунте: AboutResource.GetRequest aboutReq = Service.About.Get(); aboutReq.Fields = "user"; About about = await aboutReq.ExecuteAsync(); User user = about.User; UserName = user.DisplayName; UserEmail = user.EmailAddress; } else { DependencyService.Get <IToast>().ShortToast("Google Drive authentication canceled."); } AuthCompletedHandle.Set(); }; Auth.Error += (sender, e) => { //Debug.WriteLine("EVENT Auth.Error "); AuthenticatorErrorEventArgs err = e as AuthenticatorErrorEventArgs; DependencyService.Get <IToast>().ShortToast("GD Auth: " + err.Message + ". " + err.Exception?.ToString()); AuthCompletedHandle.Set(); }; }