Exemple #1
0
        /// <summary>
        /// Migrate users with their password
        /// </summary>
        /// <returns></returns>
        static async Task MigrateUsersWithPasswordAsync()
        {
            string appDirecotyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string dataFilePath    = Path.Combine(appDirecotyPath, Program.MigrationFile);

            // Check file existence
            if (!File.Exists(dataFilePath))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"File '{dataFilePath}' not found");
                Console.ResetColor();
                return;
            }

            // Read the data file and convert to object
            LocalAccountsModel users = LocalAccountsModel.Parse(File.ReadAllText(dataFilePath));

            // Create B2C graph client object
            B2CGraphClient b2CGraphClient = new B2CGraphClient(Program.Tenant, Program.ClientId, Program.ClientSecret);

            int successes = 0;
            int fails     = 0;

            foreach (var item in users.Users)
            {
                bool success = await b2CGraphClient.CreateAccount(
                    users.userType,
                    item.signInName,
                    item.issuer,
                    item.issuerUserId,
                    item.email,
                    item.password,
                    item.displayName,
                    item.firstName,
                    item.lastName,
                    item.extension_jdrfConsId,
                    false);

                if (success)
                {
                    successes += 1;
                }
                else
                {
                    fails += 1;
                }
            }

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"\r\nUsers migration report:\r\n\tSuccesses: {successes}\r\n\tFails: {fails} ");
            Console.ResetColor();
        }
 public async Task<ActionResult> Create(AccountModel model)
 {
     B2CGraphClient b2CGraphClient = new B2CGraphClient(_tenant, _clientId, _clientSecret);
     bool success = await b2CGraphClient.CreateAccount("emailAddress",
         model.signInName,
         model.issuer,
         model.issuerUserId,
         model.email,
         model.password,
         model.displayName,
         model.firstName,
         model.lastName,
         model.extension_jdrfConsId,
         true);
     if (success)
     {
         ViewBag.Message = "User created successfully!";
     }
     else
     {
         ViewBag.Message = "User creation failed!";
     }
     return View();
 }
        public async Task <IHttpActionResult> LoalAccountSignIn()
        {
            // If not data came in, then return
            if (this.Request.Content == null)
            {
                throw new Exception();
            }

            // Read the input claims from the request body
            string input = Request.Content.ReadAsStringAsync().Result;

            // Check input content value
            if (string.IsNullOrEmpty(input))
            {
                return(Content(HttpStatusCode.Conflict, new B2CResponseContent("Request content is empty", HttpStatusCode.Conflict)));
            }

            // Convert the input string into InputClaimsModel object
            InputClaimsModel inputClaims = JsonConvert.DeserializeObject(input, typeof(InputClaimsModel)) as InputClaimsModel;

            if (inputClaims == null)
            {
                return(Content(HttpStatusCode.Conflict, new B2CResponseContent("Can not deserialize input claims", HttpStatusCode.Conflict)));
            }

            // Note: Azure Blob Table query is case sensitive, always set the input email to lower case
            TableUserEntity userMigrationEntity = UserMigrationService.RetrieveUser(inputClaims.email.ToLower());

            if (userMigrationEntity != null)
            {
                // Compare the password entered by the user and the one in the migration table
                if (ValidateCredentials(inputClaims.email, inputClaims.password))
                {
                    Trace.WriteLine($"User '{inputClaims.email}' exists in migration table, password is matched, the service is creating new AAD account");
                    B2CGraphClient b2CGraphClient = new B2CGraphClient(this.Tenant, this.ClientId, this.ClientSecret);
                    try
                    {
                        //TBD: Read user data from your old identity provider and set the values here
                        string DisplayName = "User disaply name";
                        string FirstName   = "User first name";
                        string LastName    = "User last name";

                        // Create the user
                        await b2CGraphClient.CreateAccount(
                            "emailAddress",
                            inputClaims.email,
                            null,
                            null,
                            null,
                            inputClaims.password,
                            DisplayName,
                            FirstName,
                            LastName,
                            false);

                        // Remove the user entity from migration table
                        UserMigrationService.RemoveUser(inputClaims.email.ToLower());

                        // Wait until user is created
                        await Task.Delay(1500);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.Message);
                        return(Content(HttpStatusCode.Conflict, new B2CResponseContent("Can not migrate user", HttpStatusCode.Conflict)));
                    }
                }
                else
                {
                    Trace.WriteLine($"User '{inputClaims.email}' exists in migration table, passwords do not match");
                    return(Content(HttpStatusCode.Conflict, new B2CResponseContent("Your password is incorrect (migraion API)", HttpStatusCode.Conflict)));
                }
            }
            else
            {
                Trace.WriteLine($"No action required for user '{inputClaims.email}'");
            }
            return(Ok());
        }
        /// <summary>
        /// Migrate users with random password
        /// </summary>
        /// <returns></returns>
        static async Task MigrateUsersWithRandomPasswordAsync()
        {
            string appDirecotyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string dataFilePath    = Path.Combine(appDirecotyPath, Program.MigrationFile);

            // Check file existence
            if (!File.Exists(dataFilePath))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"File '{dataFilePath}' not found");
                Console.ResetColor();
                return;
            }

            // Read the data file and convert to object
            LocalAccountsModel users = LocalAccountsModel.Parse(File.ReadAllText(dataFilePath));

            // Create B2C graph client object
            B2CGraphClient b2CGraphClient = new B2CGraphClient(Program.Tenant, Program.ClientId, Program.ClientSecret);

            // Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Program.BlobStorageConnectionString);

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Retrieve a reference to the table.
            CloudTable table = tableClient.GetTableReference("users");

            // Create the table if it doesn't exist.
            table.CreateIfNotExists();

            // Create the batch operation.
            TableBatchOperation batchOperation = new TableBatchOperation();

            int successes = 0;
            int fails     = 0;

            foreach (var item in users.Users)
            {
                bool success = await b2CGraphClient.CreateAccount(users.userType,
                                                                  item.signInName,
                                                                  item.issuer,
                                                                  item.issuerUserId,
                                                                  item.email,
                                                                  item.password,
                                                                  item.displayName,
                                                                  item.firstName,
                                                                  item.lastName,
                                                                  true);

                // Create a new customer entity.
                // Note: Azure Blob Table query is case sensitive, always set the email to lower case
                TableEntity user = new TableEntity("B2CMigration", item.email.ToLower());

                // Create the TableOperation object that inserts the customer entity.
                TableOperation insertOperation = TableOperation.InsertOrReplace(user);

                // Execute the insert operation.
                table.Execute(insertOperation);

                if (success)
                {
                    successes += 1;
                }
                else
                {
                    fails += 1;
                }
            }


            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"\r\nUsers migration report:\r\n\tSuccesses: {successes}\r\n\tFails: {fails} ");
            Console.ResetColor();
        }
        /// <summary>
        /// Migrate users with random password
        /// </summary>
        /// <returns></returns>
        static async Task MigrateUsersWithRandomPasswordAsync()
        {
            string appDirecotyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string dataFilePath    = Path.Combine(appDirecotyPath, Program.MigrationFile);

            // Check file existence
            if (!File.Exists(dataFilePath))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"File '{dataFilePath}' not found");
                Console.ResetColor();
                return;
            }

            // Read the data file and convert to object
            LocalAccountsModel users = LocalAccountsModel.Parse(File.ReadAllText(dataFilePath));

            // Create B2C graph client object
            B2CGraphClient b2CGraphClient = new B2CGraphClient(Program.Tenant, Program.ClientId, Program.ClientSecret);

            // Create Search client object
            SearchClient searchClient = new SearchClient(new Uri(ConfigurationManager.AppSettings["AZURE_SEARCH_URI"]), ConfigurationManager.AppSettings["AZURE_SEARCH_INDEX"], new AzureKeyCredential(ConfigurationManager.AppSettings["AZURE_SEARCH_KEY"]));

            int successes = 0;
            int fails     = 0;

            foreach (var item in users.Users)
            {
                GraphAccountModel newUser = await b2CGraphClient.CreateAccount(users.userType,
                                                                               item.signInName,
                                                                               item.issuer,
                                                                               item.issuerUserId,
                                                                               item.email,
                                                                               item.password,
                                                                               item.displayName,
                                                                               item.firstName,
                                                                               item.lastName,
                                                                               item.extension_Organization,
                                                                               item.extension_UserRole,
                                                                               true);

                if (newUser != null)
                {
                    // Update the Azure Search Index
                    string signInName = string.Empty;
                    string issuer     = string.Empty;
                    string issuerId   = string.Empty;
                    string email      = string.Empty;
                    if (newUser.signInNames != null && newUser.signInNames.Count > 0)
                    {
                        signInName = newUser.signInNames[0].value;
                    }
                    if (newUser.userIdentities != null && newUser.userIdentities.Count > 0)
                    {
                        issuer   = newUser.userIdentities[0].issuer;
                        issuerId = newUser.userIdentities[0].issuerUserId;
                    }
                    if (newUser.otherMails != null && newUser.otherMails.Count > 0)
                    {
                        email = newUser.otherMails[0];
                    }
                    Document document = new Document()
                    {
                        id           = newUser.objectId,
                        signInName   = signInName,
                        issuer       = issuer,
                        issuerId     = issuerId,
                        email        = email,
                        displayName  = newUser.displayName,
                        firstName    = newUser.givenName,
                        lastName     = newUser.surname,
                        organization = newUser.extension_Organization,
                        userRole     = newUser.extension_UserRole
                    };
                    List <Document> documents = new List <Document>()
                    {
                        document
                    };
                    IndexDocumentsResult indexResults = await searchClient.MergeOrUploadDocumentsAsync(documents);

                    successes += 1;
                }
                else
                {
                    fails += 1;
                }
            }

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"\r\nUsers migration report:\r\n\tSuccesses: {successes}\r\n\tFails: {fails} ");
            Console.ResetColor();
        }