/// <summary>
        /// Creates new ActiveDirectoryClient using WindowsAzureSubscription.
        /// </summary>
        /// <param name="context"></param>
        public ActiveDirectoryClient(AzureContext context)
        {
            GraphClient = AzureSession.ClientFactory.CreateArmClient<GraphRbacManagementClient>(
                context, AzureEnvironment.Endpoint.Graph);

            GraphClient.TenantID = context.Tenant.Id.ToString();
        }
 /// <summary>
 /// Creates new ActiveDirectoryClient using WindowsAzureSubscription.
 /// </summary>
 /// <param name="context"></param>
 public ActiveDirectoryClient(AzureContext context)
 {
     AccessTokenCredential creds = (AccessTokenCredential)AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context);
     GraphClient = AzureSession.ClientFactory.CreateCustomClient<GraphRbacManagementClient>(
         creds.TenantID,
         creds,
         context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.Graph));
 }
        private static ServicePrincipalGetResult CreateServicePrincipal(ApplicationGetResult app,
                                                                        GraphRbacManagementClient graphClient)
        {
            var parameters = new ServicePrincipalCreateParameters
            {
                AccountEnabled = true,
                AppId          = app.Application.AppId
            };
            var servicePrincipal = graphClient.ServicePrincipal.Create(parameters);

            return(servicePrincipal);
        }
        public ActionResult CreateServicePrincipal()
        {
            var head = Request.Headers.GetValues(Utils.X_MS_OAUTH_TOKEN).FirstOrDefault();

            var client = new SubscriptionClient(new TokenCredentials(head));

            client.SubscriptionId = Guid.NewGuid().ToString();
            var tenants = client.Tenants.List();


            var subs   = client.Subscriptions.List();
            var cookie = ARMOAuthModule.ReadOAuthTokenCookie(HttpContext.ApplicationInstance);

            //var graphToken = AADOAuth2AccessToken.GetAccessTokenByRefreshToken(cookie.TenantId, cookie.refresh_token, "https://graph.windows.net/");

            var settings    = ActiveDirectoryServiceSettings.Azure;
            var authContext = new AuthenticationContext(settings.AuthenticationEndpoint + "common");
            var graphToken  = authContext.AcquireToken("https://management.core.windows.net/", new ClientCredential("d1b853e2-6e8c-4e9e-869d-60ce913a280c", "hVAAmWMFjX0Z0T4F9JPlslfg8roQNRHgIMYIXAIAm8s="));


            var graphClient = new GraphRbacManagementClient(new TokenCredentials(graphToken.AccessToken));

            graphClient.SubscriptionId = subs.FirstOrDefault().SubscriptionId;
            graphClient.TenantID       = tenants.FirstOrDefault().TenantId;
            //var servicePrincipals = graphClient.ServicePrincipal.List();
            try
            {
                var res = graphClient.Application.Create(new Microsoft.Azure.Graph.RBAC.Models.ApplicationCreateParameters()
                {
                    DisplayName             = "Test Application created by ARM",
                    Homepage                = "https://test.sjkp.dk",
                    AvailableToOtherTenants = false,
                    IdentifierUris          = new string[] { "https://absaad12312.sjkp.dk" },
                    ReplyUrls               = new string[] { "https://test.sjkp.dk" },
                    PasswordCredentials     = new PasswordCredential[] { new PasswordCredential()
                                                                         {
                                                                             EndDate   = DateTime.UtcNow.AddYears(1),
                                                                             KeyId     = Guid.NewGuid().ToString(),
                                                                             Value     = "s3nheiser",
                                                                             StartDate = DateTime.UtcNow
                                                                         } },
                });
            }
            catch (CloudException ex)
            {
                var s  = ex.Body.Message;
                var s2 = ex.Response.Content.AsString();
            }

            return(View());
        }
        //Get ApplicationId for the given ObjectId.
        private Guid GetApplicationId()
        {
            GraphRbacManagementClient graphClient = AzureSession.Instance.ClientFactory.CreateArmClient <GraphRbacManagementClient>(
                DefaultProfile.DefaultContext, AzureEnvironment.Endpoint.Graph);

            graphClient.TenantID = DefaultProfile.DefaultContext.Tenant.Id.ToString();

            Microsoft.Azure.Graph.RBAC.Version1_6.Models.ServicePrincipal sp = graphClient.ServicePrincipals.Get(ObjectId.ToString());

            var applicationId = Guid.Empty;

            Guid.TryParse(sp.AppId, out applicationId);
            Debug.Assert(applicationId != Guid.Empty);
            return(applicationId);
        }
        //Get ApplicationId for the given ObjectId.
        private Guid GetApplicationId()
        {
            Guid tenantId = GetTenantId(AadTenantId);

            SubscriptionCloudCredentials cred        = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(DefaultProfile.Context);
            GraphRbacManagementClient    graphClient = new GraphRbacManagementClient(tenantId.ToString(), cred);

            ServicePrincipalGetResult res = graphClient.ServicePrincipal.Get(ObjectId.ToString());

            var applicationId = Guid.Empty;

            Guid.TryParse(res.ServicePrincipal.AppId, out applicationId);
            Debug.Assert(applicationId != Guid.Empty);
            return(applicationId);
        }
        private static async Task <ApplicationInner> GetServiceApplicationInnerAsync(GraphRbacManagementClient client, string identifier)
        {
            var query = new ODataQuery <ApplicationInner>();

            var httpIdentifier  = $"http://{identifier}";
            var httpsIdentifier = $"https://{identifier}";

            if (identifier.IsGuid())
            {
                query.SetFilter(a => a.ObjectId == identifier || a.AppId == identifier);
            }
            else if (!identifier.StartsWithHttp())
            {
                query.SetFilter(a => a.IdentifierUris.Contains(httpIdentifier) || a.IdentifierUris.Contains(httpsIdentifier));
            }
            else
            {
                query.SetFilter(a => a.IdentifierUris.Contains(identifier));
            }

            try
            {
                var page = await client.Applications
                           .ListAsync(query)
                           .ConfigureAwait(false);

                var application = page.FirstOrDefault();

                while (application is null && !string.IsNullOrEmpty(page?.NextPageLink))
                {
                    page = await client.Applications
                           .ListNextAsync(page.NextPageLink)
                           .ConfigureAwait(false);

                    application = page.FirstOrDefault();
                }

                return(application);
            }
            catch (GraphErrorException)
            {
                return(null);
            }
        }
        private static async Task <UserInner> GetUserInnerAsync(GraphRbacManagementClient client, string identifier)
        {
            if (identifier.StartsWithHttp())
            {
                return(null);
            }

            if (!(identifier.IsGuid() || identifier.IsEMail()))
            {
                return(null);
            }

            if (identifier.IsEMail())
            {
                var domains = await client.Domains
                              .ListAsync()
                              .ConfigureAwait(false);

                var hasVerifiedDomain = domains
                                        .Where(d => d.IsVerified.HasValue && d.IsVerified.Value)
                                        .Any(d => identifier.EndsWith($"@{d.Name}", StringComparison.OrdinalIgnoreCase));

                if (!hasVerifiedDomain)
                {
                    var defaultDomain = domains
                                        .First(d => d.IsDefault.HasValue && d.IsDefault.Value);

                    identifier = $"{identifier.Replace("@", "_", StringComparison.OrdinalIgnoreCase)}#EXT#@{defaultDomain.Name}";
                }
            }

            try
            {
                return(await client.Users
                       .GetAsync(identifier)
                       .ConfigureAwait(false));
            }
            catch (GraphErrorException)
            {
                return(null);
            }
        }
 private static ApplicationGetResult CreateApplication(GraphRbacManagementClient graphClient, string appDisplayName, string secret)
 {
     return(graphClient.Application.Create(new ApplicationCreateParameters
     {
         DisplayName = appDisplayName,
         IdentifierUris = new List <string>()
         {
             "http://" + Guid.NewGuid().ToString() + ".com"
         },
         Homepage = "http://contoso.com",
         AvailableToOtherTenants = false,
         PasswordCredentials = new[]
         {
             new PasswordCredential
             {
                 Value = secret,
                 StartDate = DateTime.Now - TimeSpan.FromDays(1),
                 EndDate = DateTime.Now + TimeSpan.FromDays(1),
                 KeyId = Guid.NewGuid()
             }
         }
     }));
 }
        //Get ApplicationId for the given ObjectId.
        private Guid GetApplicationId()
        {
            Guid tenantId = GetTenantId(AadTenantId);

            SubscriptionCloudCredentials cred = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(DefaultProfile.Context);
            GraphRbacManagementClient graphClient = new GraphRbacManagementClient(tenantId.ToString(), cred);

            ServicePrincipalGetResult res = graphClient.ServicePrincipal.Get(ObjectId.ToString());

            var applicationId = Guid.Empty;
            Guid.TryParse(res.ServicePrincipal.AppId, out applicationId);
            Debug.Assert(applicationId != Guid.Empty);
            return applicationId;
        }
 private static ApplicationGetResult CreateApplication(GraphRbacManagementClient graphClient, string appDisplayName, string secret)
 {
     return graphClient.Application.Create(new ApplicationCreateParameters
     {
         DisplayName = appDisplayName,
         IdentifierUris = new List<string>() {"http://" + Guid.NewGuid().ToString() + ".com"},
         Homepage = "http://contoso.com",
         AvailableToOtherTenants = false,
         PasswordCredentials = new[]
         {
             new PasswordCredential
             {
                 Value = secret,
                 StartDate = DateTime.Now - TimeSpan.FromDays(1),
                 EndDate = DateTime.Now + TimeSpan.FromDays(1),
                 KeyId = Guid.NewGuid()
             }
         }
     });
 }
 private static ServicePrincipalGetResult CreateServicePrincipal(ApplicationGetResult app,
     GraphRbacManagementClient graphClient)
 {
     var parameters = new ServicePrincipalCreateParameters
     {
         AccountEnabled = true,
         AppId = app.Application.AppId
     };
     var servicePrincipal = graphClient.ServicePrincipal.Create(parameters);
     return servicePrincipal;
 }
 /// <summary>
 /// Creates new ActiveDirectoryClient using WindowsAzureSubscription.
 /// </summary>
 /// <param name="context"></param>
 public ActiveDirectoryClient(IAzureContext context)
 {
     GraphClient = AzureSession.Instance.ClientFactory.CreateArmClient <GraphRbacManagementClient>(
         context, AzureEnvironment.Endpoint.Graph);
     GraphClient.TenantID = context.Tenant.Id.ToString();
 }
        public ActionResult CreateServicePrincipal()
        {
            var head = Request.Headers.GetValues(Utils.X_MS_OAUTH_TOKEN).FirstOrDefault();

            var client = new SubscriptionClient(new TokenCredentials(head));
            client.SubscriptionId = Guid.NewGuid().ToString();
            var tenants = client.Tenants.List();

            
            var subs = client.Subscriptions.List();
            var cookie = ARMOAuthModule.ReadOAuthTokenCookie(HttpContext.ApplicationInstance);

            //var graphToken = AADOAuth2AccessToken.GetAccessTokenByRefreshToken(cookie.TenantId, cookie.refresh_token, "https://graph.windows.net/");

            var settings = ActiveDirectoryServiceSettings.Azure;
            var authContext = new AuthenticationContext(settings.AuthenticationEndpoint + "common");
            var graphToken = authContext.AcquireToken("https://management.core.windows.net/", new ClientCredential("d1b853e2-6e8c-4e9e-869d-60ce913a280c", "hVAAmWMFjX0Z0T4F9JPlslfg8roQNRHgIMYIXAIAm8s="));


            var graphClient = new GraphRbacManagementClient(new TokenCredentials(graphToken.AccessToken));

            graphClient.SubscriptionId = subs.FirstOrDefault().SubscriptionId;
            graphClient.TenantID = tenants.FirstOrDefault().TenantId;
            //var servicePrincipals = graphClient.ServicePrincipal.List();
            try
            {
                var res = graphClient.Application.Create(new Microsoft.Azure.Graph.RBAC.Models.ApplicationCreateParameters()
                {
                    DisplayName = "Test Application created by ARM",
                    Homepage = "https://test.sjkp.dk",
                    AvailableToOtherTenants = false,
                    IdentifierUris = new string[] { "https://absaad12312.sjkp.dk" },
                    ReplyUrls = new string[] { "https://test.sjkp.dk" },
                    PasswordCredentials = new PasswordCredential[] { new PasswordCredential() {
                    EndDate = DateTime.UtcNow.AddYears(1),
                    KeyId = Guid.NewGuid().ToString(),
                    Value = "s3nheiser",
                    StartDate = DateTime.UtcNow
                } },
                });

            }
            catch (CloudException ex)
            {
                var s = ex.Body.Message;
                var s2 = ex.Response.Content.AsString();

            }

            return View();
        }
Exemple #15
0
        static void Main(string[] args)
        {
            string adlaAccountName   = "<ADLA account name>";
            string resourceGroupName = "<resource group name>";
            string subscriptionId    = "<subscription ID>";

            string domain           = "<AAD tenant ID / domain>";
            var    armTokenAudience = new Uri(@"https://management.core.windows.net/");
            var    adlTokenAudience = new Uri(@"https://datalake.azure.net/");
            var    aadTokenAudience = new Uri(@"https://graph.windows.net/");

            // ----------------------------------------
            // Perform authentication to get credentials
            // ----------------------------------------

            // INTERACTIVE WITH CACHE
            var tokenCache = new TokenCache();

            tokenCache.BeforeAccess = BeforeTokenCacheAccess;
            tokenCache.AfterAccess  = AfterTokenCacheAccess;
            var armCreds = GetCredsInteractivePopup(domain, armTokenAudience, tokenCache, PromptBehavior.Auto);
            var adlCreds = GetCredsInteractivePopup(domain, adlTokenAudience, tokenCache, PromptBehavior.Auto);
            var aadCreds = GetCredsInteractivePopup(domain, aadTokenAudience, tokenCache, PromptBehavior.Auto);

            // INTERACTIVE WITHOUT CACHE
            // var armCreds = GetCredsInteractivePopup(domain, armTokenAudience, PromptBehavior.Auto);
            // var adlCreds = GetCredsInteractivePopup(domain, adlTokenAudience, PromptBehavior.Auto);
            // var aadCreds = GetCredsInteractivePopup(domain, aadTokenAudience, PromptBehavior.Auto);

            // NON-INTERACTIVE WITH SECRET KEY
            // string clientId = "<service principal / application client ID>";
            // string secretKey = "<service principal / application secret key>";
            // var armCreds = GetCredsServicePrincipalSecretKey(domain, armTokenAudience, clientId, secretKey);
            // var adlCreds = GetCredsServicePrincipalSecretKey(domain, adlTokenAudience, clientId, secretKey);
            // var aadCreds = GetCredsServicePrincipalSecretKey(domain, aadTokenAudience, clientId, secretKey);

            // NON-INTERACTIVE WITH CERT
            // string clientId = "<service principal / application client ID>";
            // var certificate = new X509Certificate2(@"<path to (PFX) certificate file>", "<certificate password>");
            // var armCreds = GetCredsServicePrincipalCertificate(domain, armTokenAudience, clientId, certificate);
            // var adlCreds = GetCredsServicePrincipalCertificate(domain, adlTokenAudience, clientId, certificate);
            // var aadCreds = GetCredsServicePrincipalCertificate(domain, aadTokenAudience, clientId, certificate);

            // ----------------------------------------
            // Create the REST clients using the credentials
            // ----------------------------------------

            var adlaAccountClient = new DataLakeAnalyticsAccountManagementClient(armCreds);

            adlaAccountClient.SubscriptionId = subscriptionId;

            var adlsAccountClient = new DataLakeStoreAccountManagementClient(armCreds);

            adlsAccountClient.SubscriptionId = subscriptionId;

            var adlaCatalogClient    = new DataLakeAnalyticsCatalogManagementClient(adlCreds);
            var adlaJobClient        = new DataLakeAnalyticsJobManagementClient(adlCreds);
            var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(adlCreds);

            var graphClient = new GraphRbacManagementClient(aadCreds);

            graphClient.TenantID = domain;

            // ----------------------------------------
            // Perform operations with the REST clients
            // ----------------------------------------

            var account = adlaAccountClient.Account.Get(resourceGroupName, adlaAccountName);

            Console.WriteLine($"My account's location is: {account.Location}!");

            // string upn = "*****@*****.**";
            // string displayName = graphClient.Users.Get(upn).DisplayName;
            // Console.WriteLine($"The display name for {upn} is {displayName}!");

            Console.ReadLine();
        }