public async Task ShouldUseUserDefinedCloudWhenEnvironmentIsSetToAUserDefinedCloud() { GraphSession.Initialize(() => new GraphSession()); // Arrange GraphEnvironment userDefinedEnvironment = new GraphEnvironment { Name = "Canary", AzureADEndpoint = "https://login.microsoftonline.com", GraphEndpoint = "https://canary.graph.microsoft.com" }; GraphSession.Instance.Environment = userDefinedEnvironment; Uri requestUrl = new Uri($"https://graph.microsoft.com/v1.0/users?{topParam}&{selectParam}"); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl); // Act var response = await this._invoker.SendAsync(httpRequestMessage, new CancellationToken()); var sentRequestQuery = response.RequestMessage.RequestUri.Query; // Assert Assert.Equal(requestUrl.Scheme, response.RequestMessage.RequestUri.Scheme); Assert.Equal("canary.graph.microsoft.com", response.RequestMessage.RequestUri.Host); Assert.Contains(topParam, sentRequestQuery); Assert.Contains($"${selectParam}", sentRequestQuery); Assert.Equal(2, sentRequestQuery.Split('&').Length); GraphSession.Reset(); }
public void ShouldSerializeAndDeserializeSettings() { GraphSession.Initialize(() => new GraphSession()); // Arrange GraphSession.Instance.DataStore = new MockDataStore(); GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); GraphEnvironment userDefinedEnv = new GraphEnvironment { Name = "TestCloud", Type = GraphEnvironmentConstants.EnvironmentType.UserDefined, AzureADEndpoint = "https://tester.com", GraphEndpoint = "https://tester.com" }; settings.EnvironmentTable[userDefinedEnv.Name] = userDefinedEnv; // Act string serializedSettings = settings.ToString(); settings.TryDeserializeObject(serializedSettings, out GraphSettings deserializedSettings, new GraphSettingsConverter()); deserializedSettings.TryGetEnvironment(userDefinedEnv.Name, out IGraphEnvironment deserializedEnv); // Assert Assert.NotNull(deserializedSettings); Assert.NotNull(deserializedEnv); Assert.Equal(serializedSettings, deserializedSettings.ToString()); Assert.Equal(userDefinedEnv.GraphEndpoint, deserializedEnv.GraphEndpoint); GraphSession.Reset(); }
public async Task ShouldUseGermanyCloudWhenEnvironmentIsSetToGermany() { GraphSession.Initialize(() => new GraphSession()); // Arrange GraphEnvironment germanyEnvironment = GraphEnvironment.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Germany]; GraphSession.Instance.Environment = germanyEnvironment; Uri requestUrl = new Uri($"https://graph.microsoft.com/beta/users?{topParam}&{selectParam}"); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl); // Act var response = await this._invoker.SendAsync(httpRequestMessage, new CancellationToken()); var sentRequestQuery = response.RequestMessage.RequestUri.Query; // Assert Assert.Equal(requestUrl.Scheme, response.RequestMessage.RequestUri.Scheme); Assert.Equal("graph.microsoft.de", response.RequestMessage.RequestUri.Host); Assert.Contains(topParam, sentRequestQuery); Assert.Contains(selectParam, sentRequestQuery); Assert.Equal(2, sentRequestQuery.Split('&').Length); GraphSession.Reset(); }
public void ShouldUseCertThumbPrintInsteadOfPassedInCertificateWhenBothAreSpecified() { // Arrange var dummyCertName = "CN=dummycert"; var inMemoryCertName = "CN=inmemorycert"; var storedDummyCertificate = CreateAndStoreSelfSignedCert(dummyCertName); var inMemoryCertificate = CreateSelfSignedCert(inMemoryCertName); AuthContext appOnlyAuthContext = new AuthContext { AuthType = AuthenticationType.AppOnly, ClientId = Guid.NewGuid().ToString(), CertificateThumbprint = storedDummyCertificate.Thumbprint, Certificate = inMemoryCertificate, ContextScope = ContextScope.Process }; // Act IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(appOnlyAuthContext); // Assert Assert.IsType <ClientCredentialProvider>(authProvider); var clientCredentialProvider = (ClientCredentialProvider)authProvider; // Assert: That the certificate used is dummycert (Thumbprint), that is in the store Assert.NotEqual(inMemoryCertName, clientCredentialProvider.ClientApplication.AppConfig.ClientCredentialCertificate.SubjectName.Name); Assert.Equal(appOnlyAuthContext.CertificateThumbprint, clientCredentialProvider.ClientApplication.AppConfig.ClientCredentialCertificate.Thumbprint); //CleanUp DeleteSelfSignedCertByThumbprint(appOnlyAuthContext.CertificateThumbprint); GraphSession.Reset(); }
public async Task ShouldUseDelegateAuthProviderWhenUserAccessTokenIsProvidedAsync() { // Arrange string accessToken = "ACCESS_TOKEN_VIA_DELEGATE_PROVIDER"; GraphSession.Instance.UserProvidedToken = new NetworkCredential(string.Empty, accessToken).SecurePassword; AuthContext userProvidedAuthContext = new AuthContext { AuthType = AuthenticationType.UserProvidedAccessToken, ContextScope = ContextScope.Process }; IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(userProvidedAuthContext); HttpRequestMessage requestMessage = new HttpRequestMessage(); // Act await authProvider.AuthenticateRequestAsync(requestMessage); // Assert Assert.IsType <DelegateAuthenticationProvider>(authProvider); Assert.Equal("Bearer", requestMessage.Headers.Authorization.Scheme); Assert.Equal(accessToken, requestMessage.Headers.Authorization.Parameter); // reset static instance. GraphSession.Reset(); }
public void ShouldThrowExceptionWhenSessionIsNotInitialized() { InvalidOperationException exception = Assert.Throws <InvalidOperationException>(() => GraphSession.Instance); Assert.Equal(ErrorConstants.Codes.SessionNotInitialized, exception.Message); // reset static instance. GraphSession.Reset(); }
public void GraphSessionShouldBeInitilizedAfterInitializerIsCalled() { GraphSession.Initialize(() => new GraphSession()); Assert.NotNull(GraphSession.Instance); Assert.Null(GraphSession.Instance.AuthContext); // reset static instance. GraphSession.Reset(); }
public void ShouldThrowExceptionWhenOutputIsNotInitialized() { GraphSession.Initialize(() => new GraphSession()); InvalidOperationException exception = Assert.Throws <InvalidOperationException>(() => GraphSession.Instance.OutputWriter.WriteObject("Output")); Assert.NotNull(GraphSession.Instance); Assert.Null(GraphSession.Instance.AuthContext); // reset static instance. GraphSession.Reset(); }
public void ShouldNotOverwriteExistingGraphSession() { GraphSession.Initialize(() => new GraphSession()); Guid originalSessionId = GraphSession.Instance._graphSessionId; GraphSession.Initialize(() => new GraphSession()); Assert.NotNull(GraphSession.Instance); Assert.Equal(originalSessionId, GraphSession.Instance._graphSessionId); // reset static instance. GraphSession.Reset(); }
public void ShouldNotOverwriteExistingGraphSession() { GraphSession.Initialize(() => new GraphSession()); Guid originalSessionId = GraphSession.Instance._graphSessionId; InvalidOperationException exception = Assert.Throws <InvalidOperationException>(() => GraphSession.Initialize(() => new GraphSession())); Assert.Equal("An instance of GraphSession already exists. Call Initialize(Func<GraphSession>, bool) to overwrite it.", exception.Message); Assert.NotNull(GraphSession.Instance); Assert.Equal(originalSessionId, GraphSession.Instance._graphSessionId); // reset static instance. GraphSession.Reset(); }
public void GetGraphHttpClientWithDefaultParametersShouldReturnHttpClientWithDefaultTimeout() { GraphSession.Initialize(() => new GraphSession()); GraphSession.Instance.AuthContext = new AuthContext { AuthType = AuthenticationType.UserProvidedAccessToken, ContextScope = ContextScope.Process }; HttpClient httpClient = HttpHelpers.GetGraphHttpClient(); Assert.Equal(GraphSession.Instance.AuthContext.ClientTimeout, TimeSpan.FromSeconds(Constants.ClientTimeout)); Assert.Equal(httpClient.Timeout, GraphSession.Instance.AuthContext.ClientTimeout); // reset static instance. GraphSession.Reset(); }
public void GetGraphHttpClientWithClientTimeoutParameterShouldReturnHttpClientWithSpecifiedTimeout() { GraphSession.Initialize(() => new GraphSession()); TimeSpan timeSpan = TimeSpan.FromSeconds(10); var authContext = new AuthContext { AuthType = AuthenticationType.UserProvidedAccessToken, ContextScope = ContextScope.Process }; IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(authContext); HttpClient httpClient = HttpHelpers.GetGraphHttpClient(authProvider, timeSpan); Assert.Equal(authContext.ClientTimeout, TimeSpan.FromSeconds(Constants.ClientTimeout)); Assert.Equal(httpClient.Timeout, timeSpan); // reset static instance. GraphSession.Reset(); }
public void ShouldInitializeOutputWriter() { GraphSessionInitializer.InitializeSession(); GraphSessionInitializer.InitializeOutput(new PsGraphOutputWriter { WriteError = (exception1, s, arg3, arg4) => _helper.WriteLine(exception1.Message), WriteObject = _helper.WriteLine, WriteDebug = _helper.WriteLine, WriteInformation = (o, s) => _helper.WriteLine(s), WriteVerbose = _helper.WriteLine }); GraphSession.Instance.OutputWriter.WriteObject("Output"); Assert.NotNull(GraphSession.Instance.OutputWriter); Assert.NotNull(GraphSession.Instance.OutputWriter.WriteObject); // reset static instance. GraphSession.Reset(); }
public void ShouldUseInteractiveProviderWhenDelegated() { // Arrange AuthContext delegatedAuthContext = new AuthContext { AuthType = AuthenticationType.Delegated, Scopes = new[] { "User.Read" }, ContextScope = ContextScope.Process }; // Act IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(delegatedAuthContext); // Assert Assert.IsType <InteractiveAuthenticationProvider>(authProvider); // reset static instance. GraphSession.Reset(); }
public void ShouldUseDeviceCodeWhenFallback() { // Arrange AuthContext delegatedAuthContext = new AuthContext { AuthType = AuthenticationType.Delegated, Scopes = new[] { "User.Read" }, ContextScope = ContextScope.Process, AuthProviderType = AuthProviderType.DeviceCodeProviderFallBack }; // Act IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(delegatedAuthContext); // Assert Assert.IsType <DeviceCodeProvider>(authProvider); // reset static instance. GraphSession.Reset(); }
public void GetGraphHttpClientShouldReturnHttpClientWithCustomerProvidedTimeout() { GraphSession.Initialize(() => new GraphSession()); TimeSpan timeSpan = TimeSpan.FromSeconds(10); GraphSession.Instance.AuthContext = new AuthContext { AuthType = AuthenticationType.UserProvidedAccessToken, ContextScope = ContextScope.Process, ClientTimeout = timeSpan }; HttpClient httpClient = HttpHelpers.GetGraphHttpClient(); Assert.Equal(GraphSession.Instance.AuthContext.ClientTimeout, timeSpan); Assert.Equal(httpClient.Timeout, timeSpan); // reset static instance. GraphSession.Reset(); }
public void ShouldLoadSettingsFromConfiguredDataStore() { GraphSession.Initialize(() => new GraphSession()); // Arrange GraphSession.Instance.DataStore = new MockDataStore(); string settingsContent = @"{ ""EnvironmentTable"": { ""MyNewCloud"": { ""Name"": ""MyNewCloud"", ""AzureADEndpoint"": ""https://login.MyNewCloud.com"", ""GraphEndpoint"": ""https://graph.MyNewCloud.com"", ""Type"": ""User-defined"" }, ""TrialCloud"": { ""Name"": ""MyNewCloud"", ""AzureADEndpoint"": ""https://login.TrialCloud.com"", ""GraphEndpoint"": ""https://graph.TrialCloud.com"", ""Type"": ""User-defined"" } } }"; GraphSession.Instance.DataStore.WriteFile(Constants.SettingFilePath, settingsContent); // Act // Loads settings from disk store. GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); settings.TryGetEnvironment("MyNewCloud", out IGraphEnvironment loadedEnvironment); // Assert Assert.NotNull(loadedEnvironment); // 5 built-in + 2 user-defined Assert.Equal(7, settings.Environments.Count()); Assert.Equal("https://login.MyNewCloud.com", loadedEnvironment.AzureADEndpoint); Assert.Equal("https://graph.MyNewCloud.com", loadedEnvironment.GraphEndpoint); Assert.Equal(GraphEnvironmentConstants.EnvironmentType.UserDefined, loadedEnvironment.Type); GraphSession.Reset(); }
public void ShouldUseInMemoryCertificateWhenProvided() { // Arrange var certificate = CreateSelfSignedCert("cn=inmemorycert"); AuthContext appOnlyAuthContext = new AuthContext { AuthType = AuthenticationType.AppOnly, ClientId = Guid.NewGuid().ToString(), Certificate = certificate, ContextScope = ContextScope.Process }; // Act IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(appOnlyAuthContext); // Assert Assert.IsType <ClientCredentialProvider>(authProvider); var clientCredentialProvider = (ClientCredentialProvider)authProvider; // Assert: That the certificate created and set above is the same as used here. Assert.Equal(clientCredentialProvider.ClientApplication.AppConfig.ClientCredentialCertificate, certificate); GraphSession.Reset(); }
public void ShouldUseClientCredentialProviderWhenAppOnlyContextIsProvided() { // Arrange AuthContext appOnlyAuthContext = new AuthContext { AuthType = AuthenticationType.AppOnly, ClientId = Guid.NewGuid().ToString(), CertificateName = "cn=dummyCert", ContextScope = ContextScope.Process }; CreateAndStoreSelfSignedCert(appOnlyAuthContext.CertificateName); // Act IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(appOnlyAuthContext); // Assert Assert.IsType <ClientCredentialProvider>(authProvider); // reset DeleteSelfSignedCertByName(appOnlyAuthContext.CertificateName); GraphSession.Reset(); }
public void ShouldSaveSettingsToConfiguredDataStore() { GraphSession.Initialize(() => new GraphSession()); // Arrange GraphSession.Instance.DataStore = new MockDataStore(); GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); GraphEnvironment userDefinedEnv = new GraphEnvironment { Name = "TestCloud", Type = GraphEnvironmentConstants.EnvironmentType.UserDefined, AzureADEndpoint = "https://tester.com", GraphEndpoint = "https://tester.com" }; string expectedSettingsContent = @"{ ""EnvironmentTable"": { ""TestCloud"": { ""Name"": ""TestCloud"", ""AzureADEndpoint"": ""https://tester.com"", ""GraphEndpoint"": ""https://tester.com"", ""Type"": ""User-defined"" } } }"; // Act // Saves settings to disk store. settings.TrySetEnvironment(userDefinedEnv, out IGraphEnvironment savedEnvironment); string settingsContent = GraphSession.Instance.DataStore.ReadFileAsText(Constants.SettingFilePath).Substring(1).TrimEnd(new[] { '\0' }); // Assert Assert.NotEmpty(settingsContent); Assert.Equal(expectedSettingsContent, settingsContent); GraphSession.Reset(); }
public void ShouldRemoveSettingsFromConfiguredDataStore() { GraphSession.Initialize(() => new GraphSession()); // Arrange GraphSession.Instance.DataStore = new MockDataStore(); GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); GraphEnvironment myNewCloudEnv = new GraphEnvironment { Name = "MyNewCloud", Type = GraphEnvironmentConstants.EnvironmentType.UserDefined, AzureADEndpoint = "https://login.MyNewCloud.com", GraphEndpoint = "https://graph.MyNewCloud.com" }; GraphEnvironment trialCloudEnv = new GraphEnvironment { Name = "TrialCloud", Type = GraphEnvironmentConstants.EnvironmentType.UserDefined, AzureADEndpoint = "https://login.TrialCloud.com", GraphEndpoint = "https://graph.TrialCloud.com" }; settings.TrySetEnvironment(myNewCloudEnv, out IGraphEnvironment mergedMyNewCloudEnv); settings.TrySetEnvironment(trialCloudEnv, out IGraphEnvironment mergedTrialCloudEnv); // Act settings.RemoveEnvironment(trialCloudEnv.Name); string settingsContent = GraphSession.Instance.DataStore.ReadFileAsText(Constants.SettingFilePath); // Assert Assert.NotEmpty(settingsContent); // 5 built-in + 1 user-defined Assert.Equal(6, settings.Environments.Count()); GraphSession.Reset(); }
public async Task ShouldUseGlobalCloudWhenEnvironmentIsNotSet() { GraphSession.Initialize(() => new GraphSession()); // Arrange GraphSession.Instance.Environment = null; string initialRequestUrl = $"https://graph.microsoft.com/v1.0/users?{topParam}&{selectParam}"; Uri requestUrl = new Uri(initialRequestUrl); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl); // Act var response = await this._invoker.SendAsync(httpRequestMessage, new CancellationToken()); var sentRequestQuery = response.RequestMessage.RequestUri.Query; // Assert Assert.Equal(requestUrl.Scheme, response.RequestMessage.RequestUri.Scheme); Assert.Equal(requestUrl.Host, response.RequestMessage.RequestUri.Host); Assert.Contains(topParam, sentRequestQuery); Assert.Contains($"${selectParam}", sentRequestQuery); Assert.Equal(2, sentRequestQuery.Split('&').Length); GraphSession.Reset(); }
/// <summary> /// Resets <see cref="GraphSession"/> instance when a user removes the module from the session via Remove-Module. /// </summary> /// <param name="psModuleInfo">A <see cref="PSModuleInfo"/> object.</param> public void OnRemove(PSModuleInfo psModuleInfo) { GraphSession.Reset(); DependencyAssemblyResolver.Reset(); }
/// <summary> /// Resets <see cref="GraphSession"/> instance when a user removes the module from the session via Remove-Module. /// </summary> /// <param name="psModuleInfo">A <see cref="PSModuleInfo"/> object.</param> public void OnRemove(PSModuleInfo psModuleInfo) { GraphSession.Reset(); }
private void CleanTokenCache(IAuthContext authContext) { TokenCacheStorage.DeleteToken(authContext); GraphSession.Reset(); }