コード例 #1
0
        public static async Task ListUsersWithCustomAttribute(GraphServiceClient graphClient, string b2cExtensionAppClientId)
        {
            if (string.IsNullOrWhiteSpace(b2cExtensionAppClientId))
            {
                throw new ArgumentException("B2cExtensionAppClientId (its Application ID) is missing from appsettings.json. Find it in the App registrations pane in the Azure portal. The app registration has the name 'b2c-extensions-app. Do not modify. Used by AADB2C for storing user data.'.", nameof(b2cExtensionAppClientId));
            }

            // Declare the names of the custom attributes
            const string customAttributeName1 = "FavouriteSeason";
            const string customAttributeName2 = "LovesPets";

            // Get the complete name of the custom attribute (Azure AD extension)
            Helpers.B2cCustomAttributeHelper helper = new Helpers.B2cCustomAttributeHelper(b2cExtensionAppClientId);
            string favouriteSeasonAttributeName     = helper.GetCompleteAttributeName(customAttributeName1);
            string lovesPetsAttributeName           = helper.GetCompleteAttributeName(customAttributeName2);

            Console.WriteLine($"Getting list of users with the custom attributes '{customAttributeName1}' (string) and '{customAttributeName2}' (boolean)");
            Console.WriteLine();

            // Get all users (one page)
            var result = await graphClient.Users
                         .Request()
                         .Select($"id,displayName,identities,{favouriteSeasonAttributeName},{lovesPetsAttributeName}")
                         .GetAsync();

            foreach (var user in result.CurrentPage)
            {
                Console.WriteLine(JsonConvert.SerializeObject(user));

                // Only output the custom attributes...
                //Console.WriteLine(JsonConvert.SerializeObject(user.AdditionalData));
            }
        }
コード例 #2
0
        private string GetIsActiveCustomAttributeName()
        {
            // Declare the names of the custom attributes
            const string customAttributeName1 = "isActive";

            // Get the complete name of the custom attribute (Azure AD extension)
            var helper = new Helpers.B2cCustomAttributeHelper(_graphApiSetting.Value.B2CExtensionAppClientId);
            var isActiveAttributeName = helper.GetCompleteAttributeName(customAttributeName1);

            return(isActiveAttributeName);
        }
コード例 #3
0
        public static async Task CreateUserWithCustomAttribute(GraphServiceClient graphClient, string b2cExtensionAppClientId, string tenantId)
        {
            if (string.IsNullOrWhiteSpace(b2cExtensionAppClientId))
            {
                throw new ArgumentException("B2C Extension App ClientId (ApplicationId) is missing in the appsettings.json. Get it from the App Registrations blade in the Azure portal. The app registration has the name 'b2c-extensions-app. Do not modify. Used by AADB2C for storing user data.'.", nameof(b2cExtensionAppClientId));
            }

            // Declare the names of the custom attributes
            const string customAttributeName1 = "FavouriteSeason";
            const string customAttributeName2 = "LovesPets";

            // Get the complete name of the custom attribute (Azure AD extension)
            Helpers.B2cCustomAttributeHelper helper = new Helpers.B2cCustomAttributeHelper(b2cExtensionAppClientId);
            string favouriteSeasonAttributeName     = helper.GetCompleteAttributeName(customAttributeName1);
            string lovesPetsAttributeName           = helper.GetCompleteAttributeName(customAttributeName2);

            Console.WriteLine($"Create a user with the custom attributes '{customAttributeName1}' (string) and '{customAttributeName2}' (boolean)");

            // Fill custom attributes
            IDictionary <string, object> extensionInstance = new Dictionary <string, object>();

            extensionInstance.Add(favouriteSeasonAttributeName, "summer");
            extensionInstance.Add(lovesPetsAttributeName, true);

            try
            {
                // Create user
                var result = await graphClient.Users
                             .Request()
                             .AddAsync(new User
                {
                    GivenName   = "Casey",
                    Surname     = "Jensen",
                    DisplayName = "Casey Jensen",
                    Identities  = new List <ObjectIdentity>
                    {
                        new ObjectIdentity()
                        {
                            SignInType       = "emailAddress",
                            Issuer           = tenantId,
                            IssuerAssignedId = "*****@*****.**"
                        }
                    },
                    PasswordProfile = new PasswordProfile()
                    {
                        Password = Helpers.PasswordHelper.GenerateNewPassword(4, 8, 4)
                    },
                    PasswordPolicies = "DisablePasswordExpiration",
                    AdditionalData   = extensionInstance
                });

                string userId = result.Id;

                Console.WriteLine($"Created the new user. Now get the created user with object ID '{userId}'...");

                // Get created user by object ID
                result = await graphClient.Users[userId]
                         .Request()
                         .Select($"id,givenName,surName,displayName,identities,{favouriteSeasonAttributeName},{lovesPetsAttributeName}")
                         .GetAsync();

                if (result != null)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine($"DisplayName: {result.DisplayName}");
                    Console.WriteLine($"{customAttributeName1}: {result.AdditionalData[favouriteSeasonAttributeName].ToString()}");
                    Console.WriteLine($"{customAttributeName2}: {result.AdditionalData[lovesPetsAttributeName].ToString()}");
                    Console.WriteLine();
                    Console.ResetColor();
                    Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
                }
            }
            catch (ServiceException ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Have you created the custom attributes '{customAttributeName1}' (string) and '{customAttributeName2}' (boolean) in your tenant?");
                    Console.WriteLine();
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();
            }
        }
コード例 #4
0
        public static async Task <User> CreateUserFromAPIMToAADB2C(GraphServiceClient graphClient, string b2cExtensionAppClientId, string tenantId, UserContract user, bool migrationEnabled, string tableConnection)
        {
            string defaultPassword = "******";

            if (string.IsNullOrWhiteSpace(b2cExtensionAppClientId))
            {
                throw new ArgumentException("B2C Extension App ClientId (ApplicationId) is missing in the appsettings.json. Get it from the App Registrations blade in the Azure portal. The app registration has the name 'b2c-extensions-app. Do not modify. Used by AADB2C for storing user data.'.", nameof(b2cExtensionAppClientId));
            }

            // Declare the names of the custom attributes
            //const string companyNameAttribute = "";


            // Get the complete name of the custom attribute (Azure AD extension)
            Helpers.B2cCustomAttributeHelper helper = new Helpers.B2cCustomAttributeHelper(b2cExtensionAppClientId);
            //string companyAttributeName = helper.GetCompleteAttributeName(companyNameAttribute);

            //Console.WriteLine($"Create a user with the custom attributes '{companyNameAttribute}' (string)");

            // Fill custom attributes
            //IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
            //extensionInstance.Add(companyAttributeName, "ValueToBeAdded");

            Microsoft.Graph.User result = null;

            try
            {
                if (migrationEnabled)
                {
                    // Create user
                    result = await graphClient.Users
                             .Request()
                             .AddAsync(new User
                    {
                        GivenName   = user.Properties.FirstName,
                        Surname     = user.Properties.LastName,
                        DisplayName = user.Properties.FirstName + " " + user.Properties.LastName,
                        Identities  = new List <ObjectIdentity>
                        {
                            new ObjectIdentity()
                            {
                                SignInType       = "emailAddress",
                                Issuer           = tenantId,
                                IssuerAssignedId = user.Properties.Email
                            }
                        },
                        PasswordProfile = new PasswordProfile()
                        {
                            //Password = Helpers.PasswordHelper.GenerateNewPassword(4, 8, 4)
                            Password = defaultPassword
                        },
                        PasswordPolicies = "DisablePasswordExpiration" //,
                                                                       //AdditionalData = extensionInstance
                    });

                    string userId = result.Id;

                    // Get created user by object ID
                    result = await graphClient.Users[userId]
                             .Request()
                             //.Select($"id,givenName,surName,displayName,identities,{companyAttributeName}")
                             .Select($"id,givenName,surName,displayName,identities")
                             .GetAsync();
                }

                if (result != null)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine($"DisplayName: {result.DisplayName}");
                    Console.WriteLine();
                    Console.ResetColor();
                    Console.ForegroundColor = ConsoleColor.White;
                    //Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
                }

                //ALB:  If we skipped the results because this is a test then add to log
                //      If we got the results then add to log
                if (result != null || !migrationEnabled)
                {
                    string jsonProps = JsonConvert.SerializeObject(user.Properties, Formatting.Indented);

                    var ats = new AzureTableService(tableConnection, "accountsLog");
                    ats.WriteSuccessEnablement(user.sourceAPIM, user.Properties.Email, jsonProps, defaultPassword, migrationEnabled);
                    //ALB:Done
                }

                return(result);
            }
            catch (ServiceException ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    //Console.WriteLine($"Have you created the custom attributes '{companyNameAttribute}' (string) in your tenant?");
                    Console.WriteLine();
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();
            }
            return(null);
        }