async Task <bool> get_authorize() { var msaAuthProvider = new MsaAuthenticationProvider( MsaClientId, MsaReturnUrl, Scopes, new CredentialVault(MsaClientId) ); try { await msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); oneDriveClient = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider); return(true); } catch (ServiceException ex) { MessageBox.Show( ex.Error.Message, "Authentication failed", MessageBoxButtons.OK); return(false); } }
//public async Task AuthenticateOneDrive() //{ // Exception error = null; // if (this.oneDriveClient == null) // { // try // { // this.IsBusy = true; // var msaAuthProvider = new MsaAuthenticationProvider(_clientId, _returnUrl, _scopes, /*CredentialCache*/ null, new CredentialVault(_clientId)); // await msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); // oneDriveClient = new OneDriveClient(this.oneDriveConsumerBaseUrl, msaAuthProvider); // } // catch (Exception ex) // { // } // if (error != null) // { // } // } //} //public async void GetAppRoot() //{ // this.IsBusy = true; // if (oneDriveClient == null) // { // AuthenticateOneDrive(); // } // //await GetFolder(oneDriveClient.Drive.Special.AppRoot, true); // var rootItem = await oneDriveClient.Drive.Root.Request().GetAsync(); // this.IsBusy = false; //} private async void InitializeClient() { var app = (App)Application.Current; if (app.OneDriveClient == null) { Task authTask; var msaAuthProvider = new MsaAuthenticationProvider( this._clientId, this._returnUrl, _scopes, new CredentialVault(this._clientId)); authTask = msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); app.OneDriveClient = new OneDriveClient(this.oneDriveConsumerBaseUrl, msaAuthProvider); app.AuthProvider = msaAuthProvider; try { await authTask; } catch (ServiceException exception) { // Swallow the auth exception but write message for debugging. Debug.WriteLine(exception.Error.Message); } } }
/// <summary> /// Perform an async Login Request /// </summary> public async Task <IOneDriveClient> LoginAsync() { try { var msaAuthenticationProvider = new MsaAuthenticationProvider( ServiceConstants.MSA_CLIENT_ID, ServiceConstants.RETURN_URL, ServiceConstants.Scopes, new CredentialVault(ServiceConstants.MSA_CLIENT_ID)); await msaAuthenticationProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); return(new OneDriveClient(ServiceConstants.BASE_URL, msaAuthenticationProvider)); } catch (ServiceException serviceException) { Debug.WriteLine(serviceException); throw new BackupException("Authentication Failed with Graph.ServiceException", serviceException); } catch (Exception ex) { Debug.WriteLine(ex); throw new BackupException("Authentication Failed", ex); } }
private async void ConnectOneDriveServer() { //이미 연결중이면 수행하지 않음. if (IsConnecting) { return; } //현재 연결이 되어 있다면 연결 해제 await DisconnectOneDriveServer(false); //연결중... IsConnecting = true; ShowErrorMessage = false; var resource = ResourceLoader.GetForCurrentView(); string errMsg = resource.GetString("Message/Error/FailServerAuthentication"); //"인증에 실패하였습니다. 아이디/패스워드를 확인하세요. "; var isOrderByName = _Sort == SortType.Name || _Sort == SortType.NameDescending; Task authTask = null; var msaAuthProvider = new MsaAuthenticationProvider( this.oneDriveConsumerClientId, this.oneDriveConsumerReturnUrl, this.scopes, new CredentialVault(this.oneDriveConsumerClientId)); await msaAuthProvider.SignOutAsync(); authTask = msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); OneDriveClient = new OneDriveClient(this.oneDriveConsumerBaseUrl, msaAuthProvider); AuthProvider = msaAuthProvider; try { await authTask; //서버타입 설정 ConnectedServerType = ServerTypes.OneDrive; await LoadOneDriveFoldersAsync(); //인증 성공 IsConnecting = false; IsDisconnected = false; } catch (ServiceException exception) { // Swallow the auth exception but write message for debugging. Debug.WriteLine(exception.Error.Message); pathStack.Clear(); IsConnecting = false; IsDisconnected = true; ShowOrderBy = false; } }
public async Task <bool> AuthenticateSaved(CancellationToken cs, string save) { msaAuthenticationProvider = new MsaAuthenticationProvider(MicrosoftSecret.ClientId, MicrosoftSecret.ClientSecret, "http://localhost:45674/authredirect", Scopes, null, new CredentialsVault(this, save)); await msaAuthenticationProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync().ConfigureAwait(false); oneDriveClient = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthenticationProvider); return(msaAuthenticationProvider.IsAuthenticated); }
public async Task GetAccountSessionAsync_SingleSignOn() { const string code = "code"; const string token = "token"; var applicationCallbackUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); this.signOut = false; this.webAuthenticationUi.responseValues = new Dictionary <string, string> { { OAuthConstants.CodeKeyName, code } }; this.webAuthenticationUi.OnAuthenticateAsync = (Uri requestUri, Uri callbackUri) => { Assert.IsTrue(requestUri.ToString().Contains("response_type=code"), "Unexpected request Uri."); Assert.IsTrue(callbackUri.ToString().Equals(applicationCallbackUrl), "Unexpected callback Uri."); }; using (var httpResponseMessage = new HttpResponseMessage()) using (var responseStream = new MemoryStream()) using (var streamContent = new StreamContent(responseStream)) { httpResponseMessage.Content = streamContent; var mockSerializer = new MockSerializer(); mockSerializer.OnDeserializeObjectStream = (Stream stream) => { mockSerializer.DeserializeObjectResponse = new Dictionary <string, string> { { OAuthConstants.AccessTokenKeyName, token } }; }; var httpProvider = new MockHttpProvider(httpResponseMessage, mockSerializer) { OnSendAsync = (HttpRequestMessage requestMessage) => { Assert.IsTrue( requestMessage.RequestUri.ToString().Equals(OAuthConstants.MicrosoftAccountTokenServiceUrl), "Unexpected token request URL."); } }; this.authenticationProvider = new MsaAuthenticationProvider( this.clientId, /* returnUrl */ null, this.scopes, this.credentialCache); this.authenticationProvider.webAuthenticationUi = this.webAuthenticationUi; await this.authenticationProvider.AuthenticateUserAsync(httpProvider).ConfigureAwait(false); Assert.IsNotNull(this.authenticationProvider.CurrentAccountSession, "No account session returned."); Assert.AreEqual(token, this.authenticationProvider.CurrentAccountSession.AccessToken, "Unexpected token returned."); } }
public async Task SignOut(string save) { if (oneDriveClient != null) { await msaAuthenticationProvider.SignOutAsync(); msaAuthenticationProvider = null; oneDriveClient = null; } }
internal async void Authenticate() { MsaAuthenticationProvider msaAuthProvider = new MsaAuthenticationProvider(clientID, "https://login.live.com/oauth20_desktop.srf", scopes); await msaAuthProvider.AuthenticateUserAsync(); OneDriveClient oneDriveClient = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider); OneDriveClient = oneDriveClient; }
private async void InitializeClient(ClientType clientType, RoutedEventArgs e) { var app = (App)Application.Current; if (app.OneDriveClient == null) { Task authTask; if (clientType == ClientType.Business) { var adalAuthProvider = new AdalAuthenticationProvider( this.oneDriveForBusinessClientId, this.oneDriveForBusinessReturnUrl); authTask = adalAuthProvider.AuthenticateUserAsync(this.oneDriveForBusinessBaseUrl); app.OneDriveClient = new OneDriveClient(this.oneDriveForBusinessBaseUrl + "/_api/v2.0", adalAuthProvider); app.AuthProvider = adalAuthProvider; } else if (clientType == ClientType.ConsumerUwp) { var onlineIdAuthProvider = new OnlineIdAuthenticationProvider( this.scopes); authTask = onlineIdAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); app.OneDriveClient = new OneDriveClient(this.oneDriveConsumerBaseUrl, onlineIdAuthProvider); app.AuthProvider = onlineIdAuthProvider; } else { var msaAuthProvider = new MsaAuthenticationProvider( this.oneDriveConsumerClientId, this.oneDriveConsumerReturnUrl, this.scopes, new CredentialVault(this.oneDriveConsumerClientId)); authTask = msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); app.OneDriveClient = new OneDriveClient(this.oneDriveConsumerBaseUrl, msaAuthProvider); app.AuthProvider = msaAuthProvider; } try { await authTask; app.NavigationStack.Add(new ItemModel(new Item())); this.Frame.Navigate(typeof(MainPage), e); } catch (ServiceException exception) { // Swallow the auth exception but write message for debugging. Debug.WriteLine(exception.Error.Message); } } else { this.Frame.Navigate(typeof(MainPage), e); } }
public async void Starter(string accessToken) { string[] scopes = new string[] { "onedrive.readonly", "wl.signin" }; var msaAuthenticationProvider = new MsaAuthenticationProvider(accessToken, "https://login.live.com/oauth20_desktop.srf", scopes); await msaAuthenticationProvider.AuthenticateUserAsync(); oneDriveClient = new OneDriveClient(msaAuthenticationProvider); Getroot(); }
public void Setup() { this.credentialCache = new MockCredentialCache(); this.webAuthenticationUi = new MockWebAuthenticationUi(); this.webAuthenticationUi.OnAuthenticateAsync = this.OnAuthenticateAsync; this.authenticationProvider = new MsaAuthenticationProvider( this.clientId, this.returnUrl, this.scopes, this.credentialCache); this.authenticationProvider.webAuthenticationUi = this.webAuthenticationUi; }
private async Task <string> AuthenticateToProvider() { const string clientId = "1e872776-dbba-47e5-8035-3e2e4ab8a4e6"; // register this under https://apps.dev.microsoft.com/ var authenticationProvider = new MsaAuthenticationProvider( clientId, "https://login.live.com/oauth20_desktop.srf", // this is the login-url for Microsoft new string[] { "wl.signin", "wl.basic" }, // https://docs.microsoft.com/en-us/previous-versions/office/developer/onedrive-live-sdk-reference/dn631845(v=office.15) new CredentialVault(clientId)); //TODO: In real app there are many more tests needed. // e.g. it is possible the restored Session from cache is valid but the attached accesstoken is already expired... await authenticationProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); return(authenticationProvider.CurrentAccountSession.AccessToken); }
public async Task InitAsync() { var authProvider = new MsaAuthenticationProvider(this.clientId, RETURN_URL, SCOPES, new CredentialVault(this.clientId)); try { await authProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); } catch (ServiceException e) { Debug.WriteLine("OneDrive auth error: " + e); throw new Exception($"OneDrive login failed: {e.Message}", e); } _oneDriveClient = new OneDriveClient(BASE_URL, authProvider); }
public async Task Login() { try { _msaAuthenticationProvider = new MsaAuthenticationProvider(APP_ID, ReturnURL, _scopes); await _msaAuthenticationProvider.AuthenticateUserAsync(); _credentialCache = _msaAuthenticationProvider.CredentialCache; _oneDriveClient = new OneDriveClient(BaseURL, _msaAuthenticationProvider); IsAuthenticated = _msaAuthenticationProvider.IsAuthenticated; } catch { } }
private async Task Authenticate(OneDriveAccount acc) { string[] scopes = { "onedrive.readwrite", "wl.signin" }; var msaAuthProvider = new MsaAuthenticationProvider( AppInfo.OneDriveClientId, /*"https://login.live.com/oauth20_desktop.srf"*/ null, scopes); await msaAuthProvider.AuthenticateUserAsync(); if (!msaAuthProvider.IsAuthenticated) { throw new Exception("Failed to authenticate One Drive client with credentials provided."); } client = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider); }
public virtual void Setup() { this.httpResponseMessage = new HttpResponseMessage(); this.credentialCache = new MockCredentialCache(); this.serializer = new MockSerializer(); this.httpProvider = new MockHttpProvider(this.httpResponseMessage, this.serializer.Object); this.webAuthenticationUi = new MockWebAuthenticationUi(); this.authenticationProvider = new MsaAuthenticationProvider( MsaAuthenticationProviderTests.ClientId, MsaAuthenticationProviderTests.ClientSecret, MsaAuthenticationProviderTests.ReturnUrl, this.scopes, this.credentialCache.Object); this.authenticationProvider.webAuthenticationUi = this.webAuthenticationUi.Object; }
public void Setup() { this.ClientId = "123456"; this.ClientSecret = "QWERTY"; this.ReturnUrl = "http://www.returnurl.com"; this.Scopes = new string[] { "Scope1", "Scope2" }; this.CredentialCache = new CredentialCache(); this.Serializer = new MockSerializer(); this.ResponseMessage = new HttpResponseMessage(); this.HttpProvider = new MockHttpProvider(this.ResponseMessage, this.Serializer); this.WebAuthenticationUi = new MockWebAuthenticationUi(); this.AuthenticationProvider = new MsaAuthenticationProvider( this.ClientId, this.ClientSecret, this.ReturnUrl, this.Scopes, this.CredentialCache, this.WebAuthenticationUi); }
public async Task <Item> GetItemsFromSelectionAsync(IOneDriveClient oneDriveClient = null) { const string msa_client_id = "0000000044128B55"; var offers = new string[] { "onedrive.readwrite", "wl.signin" }; if (oneDriveClient == null) { var authProvider = new MsaAuthenticationProvider(msa_client_id, FormBrowser.MsaReturnUrl, offers); oneDriveClient = new OneDriveClient(authProvider); await authProvider.AuthenticateUserAsync(); } var parts = this.SelectionId.Split('.'); var bundleID = parts[2]; return (await oneDriveClient.Drive.Items[bundleID].Request().Expand("thumbnails,children(expand=thumbnails)").GetAsync()); }
/// <inheritdoc/> public async Task <bool> TryAuthenticateAsync() { var refreshToken = GetRefreshToken(); if (string.IsNullOrWhiteSpace(refreshToken)) { IsAuthenticated = false; return(false); } var session = new AccountSession { ClientId = SecurityHelper.ToUnsecureString(_clientId), RefreshToken = SecurityHelper.ToUnsecureString(SecurityHelper.DecryptString(refreshToken)) }; var msaAuthProvider = new MsaAuthenticationProvider(SecurityHelper.ToUnsecureString(_clientId), "https://login.live.com/oauth20_desktop.srf", _scope) { CurrentAccountSession = session }; try { var httpProvider = new HttpProvider(new Serializer()); httpProvider.OverallTimeout = TimeSpan.FromMinutes(20); _client = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider, httpProvider); await msaAuthProvider.AuthenticateUserAsync(); IsAuthenticated = msaAuthProvider.IsAuthenticated; TokenProvider.SetToken("RefreshToken", SecurityHelper.EncryptString(SecurityHelper.ToSecureString(msaAuthProvider.CurrentAccountSession.RefreshToken))); Logger.Instance.Information($"User authenticated to {CloudServiceName}."); } catch (Exception exception) { Logger.Instance.Error(exception); IsAuthenticated = false; } return(IsAuthenticated); }
public async Task Init() { try { string clientId = "<put your client id here>"; MsaAuthenticationProvider msaAuthProvider = new MsaAuthenticationProvider(clientId, "https://login.live.com/oauth20_desktop.srf", new string[] { "onedrive.readwrite", "wl.signin" }, new CredentialVault(clientId)); await msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); oneDriveClient = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
private async Task DoTestOneDrive() { var msaAuthProvider = new MsaAuthenticationProvider( ClientId, ReturnURI, new string[] { "onedrive.readwrite", "wl.signin" }); await msaAuthProvider.AuthenticateUserAsync(); var oneDriveClient = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider); var drive = await oneDriveClient .Drive .Request() .GetAsync(); var rootItem = await oneDriveClient .Drive .Root .Request() .GetAsync(); var items = await oneDriveClient.Drive.Root.Children.Request().GetAsync(); var item1 = await oneDriveClient.Drive.Items["A13352E228C6410D!145135"].Request().GetAsync(); var builder = oneDriveClient.Drive.Root.ItemWithPath("file.txt"); var file = await builder .Request() .GetAsync(); var contentStream = await builder.Content .Request() .GetAsync(); Debug.WriteLine($"Content for file {file.Name}:"); using (var reader = new StreamReader(contentStream)) { Debug.WriteLine(reader.ReadToEnd()); } }
private async Task <bool> SignIn() { Task authTask; var msaAuthProvider = new MsaAuthenticationProvider( msaClientId, null, msaReturnUrl, scopes, null, new CredentialVault(msaClientId)); this.oneDriveClient = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider); authTask = msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); try { await authTask; } catch (ServiceException exception) { if (OAuthConstants.ErrorCodes.AuthenticationFailure == exception.Error.Code) { MessageBox.Show( "Authentication failed", "Authentication failed", MessageBoxButtons.OK); this.oneDriveClient = null; } else { PresentServiceException(exception); } return(false); } return(true); }
public static async Task <IOneDriveClient> LoginAsync(string account, string code, string settingsPassPhrase) { if (string.IsNullOrEmpty(account)) { throw new ArgumentNullException(nameof(account)); } var refreshToken = LoadRefreshToken(account, settingsPassPhrase); var authProvider = new MsaAuthenticationProvider(Secrets.CLIENT_ID, Secrets.CLIENT_SECRET, LIVE_LOGIN_DESKTOP_URI, scopes, default(CredentialCache)); var oauthHelper = new OAuthHelper(); if (!string.IsNullOrEmpty(refreshToken)) { authProvider.CurrentAccountSession = await oauthHelper.RedeemRefreshTokenAsync(refreshToken, Secrets.CLIENT_ID, Secrets.CLIENT_SECRET, LIVE_LOGIN_DESKTOP_URI, scopes); } else { if (string.IsNullOrEmpty(code)) { code = await oauthHelper.GetAuthorizationCodeAsync(Secrets.CLIENT_ID, LIVE_LOGIN_DESKTOP_URI, scopes, new WebAuthenticationUi(account)); } authProvider.CurrentAccountSession = await oauthHelper.RedeemAuthorizationCodeAsync(code, Secrets.CLIENT_ID, Secrets.CLIENT_SECRET, LIVE_LOGIN_DESKTOP_URI, scopes); if (string.IsNullOrEmpty(authProvider.CurrentAccountSession?.AccessToken)) { throw new AuthenticationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.RetrieveAuthenticationCodeFromUri, LIVE_LOGIN_AUTHORIZE_URI)); } } var client = new OneDriveClient(authProvider); SaveRefreshToken(account, authProvider.CurrentAccountSession.RefreshToken, settingsPassPhrase); return(client); }
public async Task SignOutAsync_SingleSignOn() { var applicationCallbackUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); this.signOut = true; var expectedSignOutUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}", OAuthConstants.MicrosoftAccountSignOutUrl, this.clientId, applicationCallbackUrl); this.webAuthenticationUi.OnAuthenticateAsync = (Uri requestUri, Uri callbackUri) => { Assert.AreEqual(expectedSignOutUrl, requestUri.ToString(), "Unexpected request Uri."); Assert.AreEqual(applicationCallbackUrl, callbackUri.ToString(), "Unexpected callback Uri."); }; var accountSession = new AccountSession { AccessToken = "accessToken", ClientId = "12345", }; this.authenticationProvider = new MsaAuthenticationProvider( this.clientId, /* returnUrl */ null, this.scopes, this.credentialCache); this.authenticationProvider.webAuthenticationUi = this.webAuthenticationUi; this.authenticationProvider.CurrentAccountSession = accountSession; await this.authenticationProvider.SignOutAsync().ConfigureAwait(false); Assert.IsNull(this.authenticationProvider.CurrentAccountSession, "Current account session not cleared."); Assert.IsTrue(this.credentialCache.DeleteFromCacheCalled, "DeleteFromCache not called."); }
private async Task Initialize() { if (!_initialized) { _msaAuthProvider = new MsaAuthenticationProvider(OneDriveClientId, OneDriveRedirectUri, ControlAppPagesScopes, _credentials); bool success = await DispatcherHelper.ExecuteOnUIThreadAsync(async() => { try { await _msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); return(true); } catch (Graph.ServiceException ex) when(ex.Error.Code == OAuthConstants.ErrorCodes.AuthenticationCancelled) { // Swallow it in this case. The user just cancelling is fine. System.Diagnostics.Debug.WriteLine("Authentication cancelled by user."); return(false); } }); if (!success) { return; } _httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", _msaAuthProvider.CurrentAccountSession.AccessToken); ConnectedStatus = true; var validatedPageId = await ValidatePageId(_settingsService.OneNotePageId); _settingsService.OneNotePageId = validatedPageId.ValueOr(_settingsService.OneNotePageId); if (validatedPageId.HasValue) { _initialized = true; } } }
public async Task ResotreAuthenticateUser() { byte[] cacheBlod = SettingsWorker.Current.GetCahceBlod(); if (cacheBlod == null) { return; } _credentialCache.InitializeCacheFromBlob(cacheBlod); _msaAuthenticationProvider = new MsaAuthenticationProvider(APP_ID, ReturnURL, _scopes, _credentialCache); try { await _msaAuthenticationProvider.RestoreMostRecentFromCacheAsync(); if (_msaAuthenticationProvider.IsAuthenticated) { _oneDriveClient = new OneDriveClient(BaseURL, _msaAuthenticationProvider); IsAuthenticated = true; } } catch { } }
/// <summary> /// Perform an async Login Request /// </summary> public async Task<IOneDriveClient> LoginAsync() { try { var msaAuthenticationProvider = new MsaAuthenticationProvider( ServiceConstants.MSA_CLIENT_ID, ServiceConstants.RETURN_URL, ServiceConstants.Scopes, new CredentialVault(ServiceConstants.MSA_CLIENT_ID)); await msaAuthenticationProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync(); return new OneDriveClient(ServiceConstants.BASE_URL, msaAuthenticationProvider); } catch (ServiceException serviceException) { Debug.WriteLine(serviceException); throw new BackupException("Authentication Failed with Graph.ServiceException", serviceException); } catch (Exception ex) { Debug.WriteLine(ex); throw new BackupException("Authentication Failed", ex); } }
public OneDriveController() { authProvider = new MsaAuthenticationProvider(ConfigurationManager.ClientId, ConfigurationManager.ReturnUrl, ConfigurationManager.Scopes, null, new CredentialVault(ConfigurationManager.ClientId)); }
void InitAuthenticator() { authenticator = AuthentificationHelper.GetAuthenticator(appId, "https://login.live.com/oauth20_desktop.srf", scopes); }