public async Task ServicePrincipalCertificateFileWithSecretAuthenticationTest() { var accountId = "testuser"; var certificateFile = "d:/certficatefortest.pfx"; var thumbprint = Guid.NewGuid().ToString(); var securePassword = new SecureString(); "pa88w0rd!".ToCharArray().ForEach(c => securePassword.AppendChar(c)); IDataStore prevDataStore = AzureSession.Instance.DataStore; AzureSession.Instance.DataStore = new DiskDataStore(); //Setup var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>(); mockAzureCredentialFactory.Setup(f => f.CreateClientCertificateCredential( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <X509Certificate2>(), It.IsAny <ClientCertificateCredentialOptions>())).Returns(() => new TokenCredentialMock()); AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true); InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider(); var account = new AzureAccount { Id = accountId, Type = AzureAccount.AccountType.User, }; account.SetTenants(TestTenantId); var parameter = new ServicePrincipalParameters( cacheProvider, AzureEnvironment.PublicEnvironments["AzureCloud"], null, TestTenantId, TestResourceId, account.Id, null, certificateFile, securePassword, null, null); //Run var authenticator = new ServicePrincipalAuthenticator(); var token = await authenticator.Authenticate(parameter); //Verify mockAzureCredentialFactory.Verify(f => f.CreateClientCertificateCredential(TestTenantId, accountId, It.IsAny <X509Certificate2>(), It.IsAny <ClientCertificateCredentialOptions>()), Times.Once()); Assert.Equal(fakeToken, token.AccessToken); Assert.Equal(TestTenantId, token.TenantId); AzureSession.Instance.DataStore = prevDataStore; }
public async Task ServicePrincipalCertificateFileAuthenticationTest() { var accountId = "testuser"; var certificateFile = "d:/certficatefortest.pfx"; IDataStore prevDataStore = AzureSession.Instance.DataStore; AzureSession.Instance.DataStore = new MockDataStore(); AzureSession.Instance.DataStore.WriteFile(certificateFile, "dummyfile"); //Setup var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>(); mockAzureCredentialFactory.Setup(f => f.CreateClientCertificateCredential( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <ClientCertificateCredentialOptions>())).Returns(() => new TokenCredentialMock()); AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true); InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider(); var account = new AzureAccount { Id = accountId, Type = AzureAccount.AccountType.User, }; account.SetTenants(TestTenantId); var parameter = new ServicePrincipalParameters( cacheProvider, AzureEnvironment.PublicEnvironments["AzureCloud"], null, TestTenantId, TestResourceId, account.Id, null, certificateFile, null, null, null); //Run var authenticator = new ServicePrincipalAuthenticator(); var token = await authenticator.Authenticate(parameter); //Verify mockAzureCredentialFactory.Verify(f => f.CreateClientCertificateCredential(TestTenantId, accountId, certificateFile, It.IsAny <ClientCertificateCredentialOptions>()), Times.Once()); Assert.Equal(fakeToken, token.AccessToken); Assert.Equal(TestTenantId, token.TenantId); AzureSession.Instance.DataStore = prevDataStore; }
public static void Initialize() { AzureSession.Instance.DataStore = new MemoryDataStore(); AzureRmProfileProvider.Instance.Profile = new AzureRmProfile(); PowerShellTokenCacheProvider tokenCacheProvider = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => tokenCacheProvider); IAuthenticatorBuilder builder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder); AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => new AzureCredentialFactory()); AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory()); }
void ResetState() { TestExecutionHelpers.SetUpSessionAndProfile(); ResourceManagerProfileProvider.InitializeResourceManagerProfile(true); // prevent token acquisition AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().ShouldRefreshContextsFromCache = false; AzureSession.Instance.DataStore = dataStore; AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process; AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory(); Environment.SetEnvironmentVariable("Azure_PS_Data_Collection", "false"); PowerShellTokenCacheProvider tokenProvider = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => tokenProvider, true); }
private void InitializeSession() { AzureSessionInitializer.CreateOrReplaceSession(new MemoryDataStore()); AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process; PowerShellTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => cacheProvider, true); if (!AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out IAuthenticatorBuilder builder)) { builder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder); } var profile = new AzureRmProfile { DefaultContext = defaultContext }; cmdlet.profileClient = new RMProfileClient(profile); }
public void CanAuthenticateWithAccessToken() { AzureSessionInitializer.InitializeAzureSession(); IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder); PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory); string tenant = Guid.NewGuid().ToString(); string userId = "*****@*****.**"; var armToken = Guid.NewGuid().ToString(); var graphToken = Guid.NewGuid().ToString(); var kvToken = Guid.NewGuid().ToString(); var account = new AzureAccount { Id = userId, Type = AzureAccount.AccountType.AccessToken }; account.SetTenants(tenant); account.SetAccessToken(armToken); account.SetProperty(AzureAccount.Property.GraphAccessToken, graphToken); account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, kvToken); var authFactory = new AuthenticationFactory(); var environment = AzureEnvironment.PublicEnvironments.Values.First(); var checkArmToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null); VerifyToken(checkArmToken, armToken, userId, tenant); checkArmToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.ActiveDirectoryServiceEndpointResourceId); VerifyToken(checkArmToken, armToken, userId, tenant); var checkGraphToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.GraphEndpointResourceId); VerifyToken(checkGraphToken, graphToken, userId, tenant); checkGraphToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.GraphEndpointResourceId); VerifyToken(checkGraphToken, graphToken, userId, tenant); var checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.AzureKeyVaultServiceEndpointResourceId); VerifyToken(checkKVToken, kvToken, userId, tenant); checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId); VerifyToken(checkKVToken, kvToken, userId, tenant); }
//Verify https://github.com/Azure/azure-powershell/issues/13376 public async Task SystemAssignedMSI() { var accountId = Constants.DefaultMsiAccountIdPrefix + "12345"; //Setup MockMsalAccessTokenAcquirer mockMsalAccessTokenAcquirer = SetupMockMsalAccessTokenAcquirer(); var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>(); //id must be equal to null mockAzureCredentialFactory.Setup(f => f.CreateManagedIdentityCredential(It.Is <string>(id => id == null))) .Returns(new ManagedIdentityCredential(accountId)); AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true); var account = new AzureAccount { Id = accountId, Type = AzureAccount.AccountType.ManagedService, }; account.SetTenants(TestTenantId); InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider(); var parameter = new ManagedServiceIdentityParameters( cacheProvider, AzureEnvironment.PublicEnvironments["AzureCloud"], null, TestTenantId, TestResourceId, account); //Run ManagedServiceIdentityAuthenticator authenticator = new ManagedServiceIdentityAuthenticator(); var token = await authenticator.Authenticate(parameter); //Verify var scopes = mockMsalAccessTokenAcquirer.TokenRequestContext.Scopes; Assert.True(scopes.Length == 1); Assert.Equal("https://management.core.windows.net/", scopes[0]); mockAzureCredentialFactory.Verify(); }
public void CanGetServiceClientCredentialsWithAccessToken() { AzureSessionInitializer.InitializeAzureSession(); IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder); PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory); string tenant = Guid.NewGuid().ToString(); string userId = "*****@*****.**"; var armToken = Guid.NewGuid().ToString(); var graphToken = Guid.NewGuid().ToString(); var kvToken = Guid.NewGuid().ToString(); var account = new AzureAccount { Id = userId, Type = AzureAccount.AccountType.AccessToken }; account.SetTenants(tenant); account.SetAccessToken(armToken); account.SetProperty(AzureAccount.Property.GraphAccessToken, graphToken); account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, kvToken); var authFactory = new AuthenticationFactory(); var environment = AzureEnvironment.PublicEnvironments.Values.First(); var mockContext = new AzureContext() { Account = account }; var credentials = authFactory.GetServiceClientCredentials(mockContext); VerifyAccessTokenInServiceClientCredentials(credentials, armToken); credentials = authFactory.GetServiceClientCredentials(mockContext, AzureEnvironment.Endpoint.Graph); VerifyAccessTokenInServiceClientCredentials(credentials, graphToken); credentials = authFactory.GetServiceClientCredentials(mockContext, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId); VerifyAccessTokenInServiceClientCredentials(credentials, kvToken); }
void DisableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result) { string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile); result = new ContextAutosaveSettings { Mode = ContextSaveMode.Process }; FileUtilities.DataStore = session.DataStore; session.ARMContextSaveMode = ContextSaveMode.Process; if (AzureSession.Instance.TryGetComponent( PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out PowerShellTokenCacheProvider originalTokenCacheProvider)) { if (originalTokenCacheProvider is SharedTokenCacheProvider) { var token = originalTokenCacheProvider.ReadTokenData(); //must explicitely use type PowerShellTokenCacheProvider PowerShellTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider(token); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => cacheProvider, true); } } if (AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out IAuthenticatorBuilder builder)) { builder.Reset(); } if (writeAutoSaveFile) { FileUtilities.EnsureDirectoryExists(session.ProfileDirectory); string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); session.DataStore.WriteFile(autoSavePath, JsonConvert.SerializeObject(result)); } }
public async Task SimpleSilentAuthenticationTest() { var accountId = "testuser"; //Setup var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>(); mockAzureCredentialFactory.Setup(f => f.CreateSharedTokenCacheCredentials(It.IsAny <SharedTokenCacheCredentialOptions>())).Returns(() => new TokenCredentialMock()); AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true); InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider(); var account = new AzureAccount { Id = accountId, Type = AzureAccount.AccountType.User, }; account.SetTenants(TestTenantId); var parameter = new SilentParameters( cacheProvider, AzureEnvironment.PublicEnvironments["AzureCloud"], null, TestTenantId, TestResourceId, account.Id, accountId); //Run var authenticator = new SilentAuthenticator(); var token = await authenticator.Authenticate(parameter); //Verify mockAzureCredentialFactory.Verify(); Assert.Equal(fakeToken, token.AccessToken); Assert.Equal(TestTenantId, token.TenantId); }
public void CanAuthenticateUsingMSIObjectId() { AzureSessionInitializer.InitializeAzureSession(); IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder); PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory); string expectedAccessToken = Guid.NewGuid().ToString(); _output.WriteLine("Expected access token for ARM URI: {0}", expectedAccessToken); string expectedToken2 = Guid.NewGuid().ToString(); string tenant = Guid.NewGuid().ToString(); _output.WriteLine("Expected access token for graph URI: {0}", expectedToken2); string userId = Guid.NewGuid().ToString(); var account = new AzureAccount { Id = userId, Type = AzureAccount.AccountType.ManagedService }; var environment = AzureEnvironment.PublicEnvironments["AzureCloud"]; var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId; var builder = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri); builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&object_id={userId}&api-version=2018-02-01"; var defaultUri = builder.Uri.ToString(); var customBuilder = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri); customBuilder.Query = $"resource={Uri.EscapeDataString(environment.GraphEndpointResourceId)}&object_id={userId}&api-version=2018-02-01"; var customUri = customBuilder.Uri.ToString(); var responses = new Dictionary <string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase) { { defaultUri, new ManagedServiceTokenInfo { AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource = expectedResource } }, { customUri, new ManagedServiceTokenInfo { AccessToken = expectedToken2, ExpiresIn = 3600, Resource = environment.GraphEndpointResourceId } } }; AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true); var authFactory = new AuthenticationFactory(); IRenewableToken token = (IRenewableToken)authFactory.Authenticate(account, environment, tenant, null, null, null); _output.WriteLine($"Received access token for default Uri ${token.AccessToken}"); Assert.Equal(expectedAccessToken, token.AccessToken); Assert.Equal(3600, Math.Round(token.ExpiresOn.Subtract(DateTimeOffset.Now).TotalSeconds)); var account2 = new AzureAccount { Id = userId, Type = AzureAccount.AccountType.ManagedService }; var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, AzureEnvironment.Endpoint.GraphEndpointResourceId); _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}"); Assert.Equal(expectedToken2, token2.AccessToken); var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar"); Assert.Throws <InvalidOperationException>(() => token3.AccessToken); }
/// <summary> /// Load global aliases for ARM /// </summary> public void OnImport() { #if DEBUG try { #endif AzureSessionInitializer.InitializeAzureSession(); AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer, WriteInitializationWarnings); #if DEBUG if (!TestMockSupport.RunningMocked) { #endif AzureSession.Instance.DataStore = new DiskDataStore(); #if DEBUG } #endif var autoSaveEnabled = AzureSession.Instance.ARMContextSaveMode == ContextSaveMode.CurrentUser; var autosaveVariable = System.Environment.GetEnvironmentVariable(AzureProfileConstants.AzureAutosaveVariable); if (bool.TryParse(autosaveVariable, out bool localAutosave)) { autoSaveEnabled = localAutosave; } try { if (autoSaveEnabled && !TokenCachePersistenceChecker.Verify()) { // If token cache persistence is not supported, fall back to plain text persistence, and print a warning // We cannot just throw an exception here because this is called when importing the module WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback); } } catch (Exception ex) { //Likely the exception is related permission, fall back context save mode to process autoSaveEnabled = false; AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process; WriteInitializationWarnings(Resources.FallbackContextSaveModeDueCacheCheckError.FormatInvariant(ex.Message)); } if (!InitializeProfileProvider(autoSaveEnabled)) { AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process; autoSaveEnabled = false; } IServicePrincipalKeyStore keyStore = new AzureRmServicePrincipalKeyStore(AzureRmProfileProvider.Instance.Profile); AzureSession.Instance.RegisterComponent(ServicePrincipalKeyStore.Name, () => keyStore); IAuthenticatorBuilder builder = null; if (!AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out builder)) { builder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder); } PowerShellTokenCacheProvider provider = null; if (autoSaveEnabled) { provider = new SharedTokenCacheProvider(); } else // if autosave is disabled, or the shared factory fails to initialize, we fallback to in memory { provider = new InMemoryTokenCacheProvider(); } var tokenCache = provider.GetTokenCache(); IAzureEventListenerFactory azureEventListenerFactory = new AzureEventListenerFactory(); AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => new CommonUtilities()); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => provider); AzureSession.Instance.RegisterComponent(nameof(IAzureEventListenerFactory), () => azureEventListenerFactory); AzureSession.Instance.RegisterComponent(nameof(PowerShellTokenCache), () => tokenCache); AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => new AzureCredentialFactory()); AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory()); #if DEBUG } catch (Exception) when(TestMockSupport.RunningMocked) { // This will throw exception for tests, ignore. } #endif }
/// <summary> /// Load global aliases for ARM /// </summary> public void OnImport() { #if DEBUG try { #endif AzureSessionInitializer.InitializeAzureSession(); AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer, WriteInitializationWarnings); #if DEBUG if (!TestMockSupport.RunningMocked) { #endif AzureSession.Instance.DataStore = new DiskDataStore(); #if DEBUG } #endif var autoSaveEnabled = AzureSession.Instance.ARMContextSaveMode == ContextSaveMode.CurrentUser; var autosaveVariable = System.Environment.GetEnvironmentVariable(AzureProfileConstants.AzureAutosaveVariable); if (bool.TryParse(autosaveVariable, out bool localAutosave)) { autoSaveEnabled = localAutosave; } try { if (autoSaveEnabled && !TokenCachePersistenceChecker.Verify()) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // In Windows and macOS platforms, unknown errors are discovered that fails the persistence check. // Disable context autosaving before msal library provide a fallback method for the case. throw new PSInvalidOperationException(Resources.TokenCachePersistenceCheckError); } // If token cache persistence is not supported, fall back to plain text persistence, and print a warning // We cannot just throw an exception here because this is called when importing the module WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback); } } catch (Exception ex) { //Likely the exception is related permission, fall back context save mode to process autoSaveEnabled = false; AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process; WriteInitializationWarnings(Resources.FallbackContextSaveModeDueCacheCheckError.FormatInvariant(ex.Message)); } if (!InitializeProfileProvider(autoSaveEnabled)) { AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process; autoSaveEnabled = false; } #pragma warning disable CS0618 // Type or member is obsolete var keyStore = new AzKeyStore(AzureRmProfileProvider.Instance.Profile); #pragma warning restore CS0618 // Type or member is obsolete AzureSession.Instance.RegisterComponent(AzKeyStore.Name, () => keyStore); IAuthenticatorBuilder builder = null; if (!AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out builder)) { builder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder); } PowerShellTokenCacheProvider provider = null; if (autoSaveEnabled) { provider = new SharedTokenCacheProvider(); } else // if autosave is disabled, or the shared factory fails to initialize, we fallback to in memory { provider = new InMemoryTokenCacheProvider(); } IAzureEventListenerFactory azureEventListenerFactory = new AzureEventListenerFactory(); AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => new CommonUtilities()); // It's tricky to register a component as an Interface // Make sure componentInitializer return the Interface, not the derived type AzureSession.Instance.RegisterComponent(nameof(ISharedUtilities), () => new AzureRmSharedUtilities() as ISharedUtilities); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => provider); AzureSession.Instance.RegisterComponent(nameof(IAzureEventListenerFactory), () => azureEventListenerFactory); AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => new AzureCredentialFactory()); AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory()); AzureSession.Instance.RegisterComponent <ISshCredentialFactory>(nameof(ISshCredentialFactory), () => new SshCredentialFactory()); #if DEBUG } catch (Exception) when(TestMockSupport.RunningMocked) { // This will throw exception for tests, ignore. } #endif }
public void CanAuthenticateUsingMSIDefault() { AzureSessionInitializer.InitializeAzureSession(); IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder(); AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder); PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory); var msalAccessTokenAcquirerFactory = new MsalAccessTokenAcquirerFactory(); AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => msalAccessTokenAcquirerFactory, true); string expectedAccessToken = Guid.NewGuid().ToString(); _output.WriteLine("Expected access token for default URI: {0}", expectedAccessToken); var mockAzureCredentialFactory = new MockAzureCredentialFactory(); MockManagedIdentityCredential mockManagedIdentityCredential = null; mockAzureCredentialFactory.CredentialFactory = (clientId) => { return(mockManagedIdentityCredential = new MockManagedIdentityCredential(clientId) { TokenFactory = () => new AccessToken(expectedAccessToken, DateTimeOffset.Now) }); }; AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => (AzureCredentialFactory)mockAzureCredentialFactory, true); string expectedToken2 = Guid.NewGuid().ToString(); string tenant = Guid.NewGuid().ToString(); _output.WriteLine("Expected access token for custom URI: {0}", expectedToken2); string userId = Constants.DefaultMsiAccountIdPrefix + "12345"; var account = new AzureAccount { Id = userId, Type = AzureAccount.AccountType.ManagedService }; var environment = AzureEnvironment.PublicEnvironments["AzureCloud"]; var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId; var builder = new UriBuilder(AuthenticationFactory.DefaultBackupMSILoginUri); //builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&api-version=2018-02-01"; //var defaultUri = builder.Uri.ToString(); //var responses = new Dictionary<string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase) //{ // {defaultUri, new ManagedServiceTokenInfo { AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource=expectedResource}}, // {"http://*****:*****@foo.com"; var account2 = new AzureAccount { Id = userId2, Type = AzureAccount.AccountType.ManagedService }; //account2.SetProperty(AzureAccount.Property.MSILoginUri, "http://myfunkyurl:10432/oauth2/token"); expectedAccessToken = expectedToken2; var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, "foo"); _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}"); Assert.Equal(expectedToken2, token2.AccessToken); Assert.Equal(userId2, mockManagedIdentityCredential.AccountId); //var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar"); //Assert.Throws<InvalidOperationException>(() => token3.AccessToken); }
void DisableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result) { string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile); result = new ContextAutosaveSettings { Mode = ContextSaveMode.Process }; FileUtilities.DataStore = session.DataStore; session.ARMContextSaveMode = ContextSaveMode.Process; PowerShellTokenCacheProvider cacheProvider; MemoryStream memoryStream = null; if (AzureSession.Instance.TryGetComponent( PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out PowerShellTokenCacheProvider originalTokenCacheProvider)) { if (originalTokenCacheProvider is SharedTokenCacheProvider) { cacheProvider = new InMemoryTokenCacheProvider(); var token = originalTokenCacheProvider.ReadTokenData(); if (token != null && token.Length > 0) { memoryStream = new MemoryStream(token); } cacheProvider.UpdateTokenDataWithoutFlush(token); cacheProvider.FlushTokenData(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => cacheProvider, true); } else { cacheProvider = originalTokenCacheProvider; } } else { cacheProvider = new InMemoryTokenCacheProvider(); } PowerShellTokenCache newTokenCache = null; if (AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCache), out PowerShellTokenCache tokenCache)) { if (!tokenCache.IsPersistentCache) { newTokenCache = tokenCache; } else { newTokenCache = memoryStream == null ? null : PowerShellTokenCache.Deserialize(memoryStream); } } if (newTokenCache == null) { newTokenCache = cacheProvider.GetTokenCache(); } AzureSession.Instance.RegisterComponent(nameof(PowerShellTokenCache), () => newTokenCache, true); if (AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out IAuthenticatorBuilder builder)) { builder.Reset(); } if (writeAutoSaveFile) { FileUtilities.EnsureDirectoryExists(session.ProfileDirectory); string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); session.DataStore.WriteFile(autoSavePath, JsonConvert.SerializeObject(result)); } }