Exemplo n.º 1
0
        public void CanAuthenticateUsingMSIObjectId()
        {
            AzureSessionInitializer.InitializeAzureSession();
            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);
            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);
            Assert.Equal(3600, Math.Round(token.ExpiresOn.DateTime.Subtract(DateTime.UtcNow).TotalSeconds));
            var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");

            Assert.Throws <InvalidOperationException>(() => token3.AccessToken);
        }
Exemplo n.º 2
0
        public void CanAuthenticateUsingMSIDefault()
        {
            AzureSessionInitializer.InitializeAzureSession();
            string expectedAccessToken = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for default URI: {0}", expectedAccessToken);
            string expectedToken2 = Guid.NewGuid().ToString();
            string tenant         = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for custom URI: {0}", expectedToken2);
            string userId  = "*****@*****.**";
            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://myfunkyurl:10432/oauth2/token?resource=foo&api-version=2018-02-01", new ManagedServiceTokenInfo {
                      AccessToken = expectedToken2, ExpiresIn = 3600, Resource = "foo"
                  } }
            };

            AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true);
            var authFactory = new AuthenticationFactory();
            var token       = authFactory.Authenticate(account, environment, tenant, null, null, null);

            _output.WriteLine($"Received access token for default Uri ${token.AccessToken}");
            Assert.Equal(expectedAccessToken, token.AccessToken);
            var account2 = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };

            account2.SetProperty(AzureAccount.Property.MSILoginUri, "http://myfunkyurl:10432/oauth2/token");
            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);
            var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");

            Assert.Throws <InvalidOperationException>(() => token3.AccessToken);
        }
Exemplo n.º 3
0
        /// Get the access token for a service principal and provided key.
        public static TokenCloudCredentials GetTokenCloudCredentials(string tenantId, string clientId, SecureString secretKey)
        {
            var authFactory = new AuthenticationFactory();
            var account     = new AzureAccount {
                Type = AzureAccount.AccountType.ServicePrincipal, Id = clientId
            };
            var env         = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
            var accessToken =
                authFactory.Authenticate(account, env, tenantId, secretKey, ShowDialog.Never).AccessToken;

            return(new TokenCloudCredentials(accessToken));
        }
        public void VerifyValidateAuthorityFalseForOnPremise()
        {
            var authFactory = new AuthenticationFactory
            {
                TokenProvider = new MockAccessTokenProvider("testtoken", "testuser")
            };

            var subscriptionId = Guid.NewGuid();
            var context        = new AzureContext
                                 (
                new AzureSubscription
            {
                Id         = subscriptionId,
                Properties = new Dictionary <AzureSubscription.Property, string>
                {
                    { AzureSubscription.Property.Tenants, "123" }
                }
            },
                new AzureAccount
            {
                Id         = "testuser",
                Type       = AzureAccount.AccountType.User,
                Properties = new Dictionary <AzureAccount.Property, string>
                {
                    { AzureAccount.Property.Tenants, "123" }
                }
            },
                new AzureEnvironment
            {
                Name      = "Katal",
                OnPremise = true,
                Endpoints = new Dictionary <AzureEnvironment.Endpoint, string>
                {
                    { AzureEnvironment.Endpoint.ActiveDirectory, "http://ad.com" },
                    { AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, "http://adresource.com" }
                }
            }
                                 );

            var credential = authFactory.Authenticate(context.Account, context.Environment, "common", null, ShowDialog.Always);

            Assert.False(((MockAccessTokenProvider)authFactory.TokenProvider).AdalConfiguration.ValidateAuthority);
        }
Exemplo n.º 5
0
        private static TokenCredentials Authenticate()
        {
            var authFactory = new AuthenticationFactory();
            var account     = new AzureAccount
            {
                Type = _isServicePrincipal
                    ? AzureAccount.AccountType.ServicePrincipal
                    : AzureAccount.AccountType.User
            };

            if (_userName != null && (_password != null || _isServicePrincipal))
            {
                account.Id = _userName;
            }

            var env = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];

            var tenant = string.IsNullOrEmpty(_tenantId)
                ? AuthenticationFactory.CommonAdTenant
                : _tenantId;

            ShowDialog showDialog;

            if (_isServicePrincipal)
            {
                showDialog = ShowDialog.Never;
            }
            else if (_userName != null && _password == null)
            {
                showDialog = ShowDialog.Always;
            }
            else
            {
                showDialog = ShowDialog.Auto;
            }

            var authResult = authFactory.Authenticate(
                account, env, tenant, _password, showDialog);

            return(new TokenCredentials(authResult.AccessToken));
        }
Exemplo n.º 6
0
        public void VerifyValidateAuthorityFalseForOnPremise()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var authFactory = new AuthenticationFactory
            {
                TokenProvider = new MockAccessTokenProvider("testtoken", "testuser")
            };

            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "testuser",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("123");
            var sub = new AzureSubscription
            {
                Id = subscriptionId.ToString(),
            };

            sub.SetTenant("123");
            var context = new AzureContext
                          (
                sub,
                account,
                new AzureEnvironment
            {
                Name      = "Katal",
                OnPremise = true,
                ActiveDirectoryAuthority = "http://ad.com",
                ActiveDirectoryServiceEndpointResourceId = "http://adresource.com"
            }
                          );

            var credential = authFactory.Authenticate(context.Account, context.Environment, "common", null, ShowDialog.Always, null);

            Assert.False(((MockAccessTokenProvider)authFactory.TokenProvider).AdalConfiguration.ValidateAuthority);
        }
Exemplo n.º 7
0
        public static TokenCloudCredentials GetTokenCloudCredentials(string username = null, SecureString password = null)
        {
            var authFactory = new AuthenticationFactory();

            var account = new AzureAccount {
                Type = AzureAccount.AccountType.User
            };

            if (username != null && password != null)
            {
                account.Id = username;
            }

            var env = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];

            ShowDialog dialog = username != null & password != null ? ShowDialog.Never : ShowDialog.Always;

            var accessToken =
                authFactory.Authenticate(account, env, AuthenticationFactory.CommonAdTenant, password, dialog)
                .AccessToken;

            return(new TokenCloudCredentials(accessToken));
        }
Exemplo n.º 8
0
        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);
        }
        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);
        }