コード例 #1
0
        public async Task <string> DeleteUser(GraphObject graphObject)
        {
            var client   = new B2CGraphClient(clientId, clientSecret, tenant);
            var response = await client.DeleteUser(graphObject.UserId);

            return(response);
        }
コード例 #2
0
 public async Task<ActionResult> Edit(AccountModel model)
 {
     B2CGraphClient b2CGraphClient = new B2CGraphClient(_tenant, _clientId, _clientSecret);
     await b2CGraphClient.UpdateUser(model.signInName, model.displayName, model.firstName, model.lastName, model.extension_jdrfConsId);
     ViewBag.Message = "User updated successfully!";
     return View();
 }
コード例 #3
0
        /// <summary>
        /// Migration clean up
        /// </summary>
        /// <returns></returns>
        static async Task UserMigrationCleanupAsync()
        {
            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);

            foreach (var item in users.Users)
            {
                Console.WriteLine($"Deleting user '{item.email}'");
                await b2CGraphClient.DeleteAADUserBySignInNames(item.email);
            }
        }
コード例 #4
0
        public async Task <string> UpdateFeedPreference(GraphObject graphObject)
        {
            var client   = new B2CGraphClient(clientId, clientSecret, tenant);
            var response = await client.UpdateUser(graphObject.UserId, graphObject.UserJsonData);

            return(response);
        }
コード例 #5
0
ファイル: AuthService.cs プロジェクト: xtophs/SPP_Public
        private async Task DeleteUserAD(string objectId)
        {
            try
            {
                //Obtain B2C Settings
                var b2cDB = new ADB2CSettings()
                {
                    Id = 1
                };
                var b2cSettings = await _db.GetAsync(b2cDB);

                //Use Microsoft Graph to perform action on Azure AD B2C
                var client = new B2CGraphClient(
                    b2cSettings.AadClientId,
                    b2cSettings.AadClientSecret,
                    b2cSettings.AadTenant,
                    b2cSettings.AadGraphResourceId,
                    b2cSettings.AadGraphEndpoint,
                    b2cSettings.AadGraphVersion);
                await client.DeleteUser(objectId);
            }
            catch (Exception)
            {
                //Ignore if no AAD user is found
            }
        }
コード例 #6
0
        public async Task <ActionResult> Claims()
        {
            var userObjectId = ClaimsPrincipal.Current.Claims
                               .Where(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")
                               .Select(x => x.Value)
                               .FirstOrDefault();

            var model = ClaimsPrincipal.Current.Claims
                        .Select(x => new Claim(x.Type, x.Value))
                        .ToList();

            if (userObjectId != null)
            {
                var b2cGraph   = new B2CGraphClient();
                var userGroups = await b2cGraph.GetUserGroups(userObjectId);

                var aggregatedGroups = string.Empty;

                foreach (var userGroup in userGroups)
                {
                    if (aggregatedGroups != string.Empty)
                    {
                        aggregatedGroups += " ";
                    }

                    aggregatedGroups += userGroup.DisplayName;
                }

                model.Add(new Claim("USER_GROUPS", aggregatedGroups));
            }
            ViewBag.Message = "Your application description page.";
            return(View(model));
        }
コード例 #7
0
        public async Task ListAllUsers()
        {
            var client = new B2CGraphClient("aeefcc33-b5b3-4997-90e9-817e0d91d068", Secret, "b6bdfb2f-60a9-48b4-9fa5-5c15a97e4ffb");

            var users = await client.GetAllUsers();

            Console.WriteLine(JObject.Parse(users).ToString(Formatting.Indented));
        }
コード例 #8
0
        public async Task <IActionResult> Delete()
        {
            var userObjectIdentifier = HttpContext.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");

            var client = new B2CGraphClient(_tenantAdminOptions.ClientId, _tenantAdminOptions.ClientSecret, _tenantAdminOptions.Tenant);

            await client.DeleteUser(userObjectIdentifier.Value);

            return(await SignOut());
        }
コード例 #9
0
        static void Main(string[] args)
        {
            client = new B2CGraphClient(Globals.clientId, Globals.clientSecret, Globals.tenant);

            var    result    = client.GetUserByObjectId("f7e5b82b-1377-4e1e-a9bf-9611d84436b9").Result;
            object formatted = JsonConvert.DeserializeObject(result);

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(JsonConvert.SerializeObject(formatted, Formatting.Indented));
        }
コード例 #10
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();
        }
コード例 #11
0
        public async Task CreateUserTest()
        {
            var client = new B2CGraphClient("aeefcc33-b5b3-4997-90e9-817e0d91d068", Secret, "b6bdfb2f-60a9-48b4-9fa5-5c15a97e4ffb");

            var userTemplate = JObject.Parse(new StreamReader(typeof(B2CGraphClient).Assembly.GetManifestResourceStream("IdentityServer.AzureAdUserService.CreateUserTemplate.json")).ReadToEnd());

            (userTemplate.SelectToken("alternativeSignInNamesInfo[0].type").Parent as JProperty).Value  = "userName"; // "emailAddress";
            (userTemplate.SelectToken("alternativeSignInNamesInfo[0].value").Parent as JProperty).Value = "myUserName";
            (userTemplate.SelectToken("passwordProfile.password").Parent as JProperty).Value            = "P@ssword!";


            Console.WriteLine(JObject.Parse(await client.CreateUser(userTemplate.ToString())).ToString(Formatting.Indented));
        }
コード例 #12
0
        internal bool UpdateB2C(Dictionary <string, string> updates, string userId)
        {
            if (String.IsNullOrEmpty(userId))
            {
                return(false);
            }
            AADUser        aad    = new AADUser(tenant, id, secret);
            B2CGraphClient b2c    = new B2CGraphClient(id, secret, tenant);
            string         result = b2c.UpdateUser(userId, JsonConvert.SerializeObject(updates)).Result;

            if (!result.Contains("Error"))
            {
                return(true);
            }
            return(false);
        }
コード例 #13
0
        public async Task<ActionResult> FindPost()
        {
            string emailAddress = Request.Form["emailAddress"];
            B2CGraphClient b2CGraphClient = new B2CGraphClient(_tenant, _clientId, _clientSecret);
            string json = await b2CGraphClient.SearcUserBySignInNames(emailAddress);
            GraphAccounts graphAccounts = GraphAccounts.Parse(json);

            if (graphAccounts != null && graphAccounts.value != null)
            {
                return RedirectToAction("Edit", new { emailAddress = emailAddress });
            }
            else
            {
                ViewBag.Message = "User not found!";
            }

            return View();
        }
コード例 #14
0
ファイル: AuthService.cs プロジェクト: xtophs/SPP_Public
        private async Task <ADUser> CreateUserAD(UserDto user)
        {
            //Obtain B2C Settings
            var b2cDB = new ADB2CSettings()
            {
                Id = 1
            };
            var b2cSettings = await _db.GetAsync(b2cDB);

            //Create a new user object
            var userObject = new JObject
            {
                { "accountEnabled", true },
                { "creationType", "LocalAccount" },
                { "displayName", user.FullName },
                { "passwordProfile", new JObject
                  {
                      { "password", "WSXzaq!23" },
                      { "forceChangePasswordNextLogin", true }
                  } },
                { "signInNames", new JArray
                  {
                      new JObject
                      {
                          { "type", "emailAddress" },
                          { "value", user.Email.Trim() }
                      }
                  } }
            };

            //Use Microsoft Graph to perform action on Azure AD B2C
            var client = new B2CGraphClient(
                b2cSettings.AadClientId,
                b2cSettings.AadClientSecret,
                b2cSettings.AadTenant,
                b2cSettings.AadGraphResourceId,
                b2cSettings.AadGraphEndpoint,
                b2cSettings.AadGraphVersion);
            var response = await client.CreateUser(userObject.ToString());

            var newUser = JsonConvert.DeserializeObject <ADUser>(response);

            return(newUser);
        }
コード例 #15
0
        public async Task<ActionResult> Edit(string emailAddress)
        {
            AccountModel model;
            B2CGraphClient b2CGraphClient = new B2CGraphClient(_tenant, _clientId, _clientSecret);
            GraphAccountModel user = await b2CGraphClient.GetUser(emailAddress);

            if (user != null)
            {
                model = new AccountModel()
                {
                    signInName = user.signInNames[0].value,
                    displayName = user.displayName,
                    firstName = user.givenName,
                    lastName = user.surname,
                    extension_jdrfConsId = user.extension_jdrfConsId
                };
            }
            else
            {
                return RedirectToAction("Find");
            }

            return View(model);
        }
コード例 #16
0
 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();
 }
コード例 #17
0
 public B2CUserManager(B2CGraphClient graphClient)
 {
     this._graphClient = graphClient;
 }
コード例 #18
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {
                string id = req.Query["id"];
                log.LogInformation("Query: " + req.Query);
                log.LogInformation(id);

                if (!String.IsNullOrEmpty(id))
                {
                    string tenant         = _appSettings.B2CTenantId;
                    string clientId       = _appSettings.B2CGraphAccessClientId.ToString();
                    string clientSecret   = _appSettings.B2CGraphAccessClientSecret;
                    string extensionAppId = _appSettings.ExtensionAppId;
                    log.LogInformation("tenant: " + tenant);

                    B2CGraphClient client = new B2CGraphClient(clientId, clientSecret, tenant);

                    var getUserApiResponse = await client.GetUserByObjectId(id);

                    if (!String.IsNullOrEmpty(getUserApiResponse))
                    {
                        var user = JsonConvert.DeserializeObject <UserValueModel>(getUserApiResponse);
                        if (user == null || String.IsNullOrEmpty(user.objectId))
                        {
                            return(new BadRequestObjectResult(new ResponseContentModel
                            {
                                userMessage = "No such a user exist. Please check the Object Id"
                            }));
                        }
                        else
                        {
                            JObject obj        = JObject.Parse(getUserApiResponse);
                            var     customerId = obj["extension_" + extensionAppId + "_customerId"];
                            return((ActionResult) new OkObjectResult(new { FirstName = user.givenName, LastName = user.surname, DisplayName = user.displayName, Email = user.signInNames.FirstOrDefault().value, CustomerId = customerId }));
                        }
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "No such a user exist. Please check the Object Id"
                        }));
                    }
                }
                else
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Invalid input, Object Id cannot be null"
                    }));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Sorry, something happened unexpectedly. Please try again later.",
                    developerMessage = "See logging provider failure dependencies for exception information."
                }));
            }
        }
コード例 #19
0
        public async Task <IActionResult> Register([FromBody] RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var client = new HttpClient();

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Icr78VL86Up+ZxLdv+OR5aQVKov2rsg9wzVfXKZpbAg=");

                /* OAuth2 is required to access this API. For more information visit:
                 * https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks */

                // Specify values for path parameters (shown as {...})
                var uri = "https://graph.windows.net/chsakellhotmail.onmicrosoft.com/users?api-version=1.6";

                var jsonObject = new JObject
                {
                    { "accountEnabled", true },
                    { "creationType", "LocalAccount" },
                    { "displayName", model.Username.Trim() },
                    { "passwordPolicies", "DisablePasswordExpiration,DisableStrongPassword" },
                    { "passwordProfile", new JObject
                      {
                          { "password", model.Password },
                          { "forceChangePasswordNextLogin", false }
                      } },
                    { "signInNames", new JArray
                      {
                          new JObject
                          {
                              { "value", model.Email.Trim() },
                              { "type", "emailAddress" }
                          }
                      } }
                };

                try
                {
                    var b2cClient = new B2CGraphClient(ClientId, ClientSecret, TenantId);
                    var response  = await b2cClient.CreateUser(jsonObject.ToString());

                    var adUser = JsonConvert.DeserializeObject <ActiveDirectoryUser>(response);

                    if (adUser != null)
                    {
                        return(Ok(new ResultViewModel()
                        {
                            Result = Result.SUCCESS,
                            Data = new { username = adUser.SignInNames[0].Value, id = adUser.ObjectId, redirect = true }
                        }));
                    }
                    else
                    {
                        return(Ok(new ResultViewModel()
                        {
                            Result = Result.ERROR,
                            Message = "Something went wrong"
                        }));
                    }
                }
                catch (Exception ex)
                {
                }
            }

            return(BadRequest(new ResultViewModel()
            {
                Result = Result.ERROR,
                Message = "Bad request"
            }));
        }
コード例 #20
0
        static void Main(string[] args)
        {
            if (args.Length <= 0)
            {
                Console.WriteLine("Please enter a command as the first argument.");
                Console.WriteLine("\t1                 : Migrate social and local accounts with password");
                Console.WriteLine("\t2                 : Migrate social and local accounts with random password");
                Console.WriteLine("\t3 Email-address  : Get user by email address");
                Console.WriteLine("\t4 Display-name   : Get user by display name");
                Console.WriteLine("\t5                : User migration cleanup");
                return;
            }

            try
            {
                switch (args[0])
                {
                case "1":
                    MigrateUsersWithPasswordAsync().Wait();
                    break;

                case "2":
                    MigrateUsersWithRandomPasswordAsync().Wait();
                    break;

                case "3":
                    if (args.Length == 2)
                    {
                        B2CGraphClient b2CGraphClient = new B2CGraphClient(Program.Tenant, Program.ClientId, Program.ClientSecret);
                        string         JSON           = b2CGraphClient.SearcUserBySignInNames(args[1]).Result;

                        Console.WriteLine(JSON);
                        GraphAccounts users = GraphAccounts.Parse(JSON);
                    }
                    else
                    {
                        Console.WriteLine("Email address parameter is missing");
                    }
                    break;

                case "4":
                    if (args.Length == 2)
                    {
                        B2CGraphClient b2CGraphClient = new B2CGraphClient(Program.Tenant, Program.ClientId, Program.ClientSecret);
                        string         JSON           = b2CGraphClient.SearchUserByDisplayName(args[1]).Result;

                        Console.WriteLine(JSON);
                        GraphAccounts users = GraphAccounts.Parse(JSON);
                    }
                    else
                    {
                        Console.WriteLine("Display name parameter is missing");
                    }
                    break;

                case "5":
                    UserMigrationCleanupAsync().Wait();
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);
                }
                else
                {
                    Console.WriteLine(ex.Message);
                }
            }
            finally
            {
                Console.ResetColor();
            }

            Console.ReadLine();
        }
コード例 #21
0
        /// <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();
        }
コード例 #22
0
        static async Task Main(string[] args)
        {
            var tenantName    = "";
            var applicationId = "";
            var clientSecret  = "";

            var storageName = "";
            var storagekey  = "";

            var b2cGraphClient = new B2CGraphClient(tenantName, applicationId, clientSecret);

            var response = await b2cGraphClient.GetAllUsersAsync();

            var accounts = GraphAccounts.Parse(response);

            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageName, storagekey), true);

            //Client
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            //Table
            CloudTable table = tableClient.GetTableReference("Ticket");

            TableQuery <TicketTableEntity> query = new TableQuery <TicketTableEntity>();

            List <TicketTableEntity> results           = new List <TicketTableEntity>();
            TableContinuationToken   continuationToken = null;

            do
            {
                TableQuerySegment <TicketTableEntity> queryResults =
                    await table.ExecuteQuerySegmentedAsync(query, continuationToken);

                continuationToken = queryResults.ContinuationToken;
                results.AddRange(queryResults.Results);
            } while (continuationToken != null);

            using (var textWriter = new StreamWriter("accounts.csv"))
            {
                var csv = new CsvWriter(textWriter);

                csv.WriteHeader <CsvItem>();
                csv.NextRecord();

                foreach (var account in accounts.value)
                {
                    var tickets = results.Where(x => x.AttendeeId == account.Id);

                    if (tickets.Count() == 0)
                    {
                        var item = new CsvItem
                        {
                            Id        = account.Id,
                            Email     = account.OtherMails.FirstOrDefault(),
                            FirstName = account.GivenName,
                            LastName  = account.Surname,
                        };
                        csv.WriteRecord(item);
                        csv.NextRecord();
                    }

                    foreach (var ticket in tickets)
                    {
                        var item = new CsvItem
                        {
                            Id          = account.Id,
                            Email       = account.OtherMails.FirstOrDefault(),
                            FirstName   = account.GivenName,
                            LastName    = account.Surname,
                            TicketType  = ticket.TicketType,
                            CouponCode  = ticket.CouponCode,
                            IsPayed     = ticket.IsPayed,
                            PaymentType = ticket.PaymentType,
                            Price       = ticket.Price,
                            WorkshopId  = ticket.WorkshopId,
                            City        = account.city,
                            Company     = account.extension_d6245cc8578e4908b91662ccd12132e2_Company,
                            JobTitle    = account.jobTitle
                        };

                        csv.WriteRecord(item);
                        csv.NextRecord();
                    }
                }
                csv.Flush();
                csv.Dispose();
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "put", Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {
                string           requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                UserProfileModel data        = JsonConvert.DeserializeObject <UserProfileModel>(requestBody);

                var results = new List <ValidationResult>();

                Validator.TryValidateObject(data, new ValidationContext(data, null, null), results, true);

                if (results.Count > 0)
                {
                    var rvalidationResponse = results.Select(p => new ResponseContentModel {
                        version = "1.0.0", userMessage = p.ErrorMessage
                    });
                    return(new BadRequestObjectResult(rvalidationResponse));
                }

                log.LogInformation(requestBody);

                if (data != null)
                {
                    if (String.IsNullOrEmpty(data.ObjectId))
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            version = "1.0.0",
                            userMessage = "Object id can't be null"
                        }));
                    }



                    if (String.IsNullOrEmpty(data.DisplayName))
                    {
                        data.DisplayName = data.FirstName + " " + data.LastName;
                    }

                    string         tenant       = _appSettings.B2CTenantId;                       // Environment.GetEnvironmentVariable("B2CTenantId", EnvironmentVariableTarget.Process);
                    string         clientId     = _appSettings.B2CGraphAccessClientId.ToString(); // Environment.GetEnvironmentVariable("B2CGraphAccessClientId", EnvironmentVariableTarget.Process);
                    string         clientSecret = _appSettings.B2CGraphAccessClientSecret;        // Environment.GetEnvironmentVariable("B2CGraphAccessClientSecret", EnvironmentVariableTarget.Process);
                    B2CGraphClient client       = new B2CGraphClient(clientId, clientSecret, tenant);

                    var getUserApiResponse = await client.GetUserByObjectId(data.ObjectId);

                    if (!String.IsNullOrEmpty(getUserApiResponse))
                    {
                        var user = JsonConvert.DeserializeObject <UserValueModel>(getUserApiResponse);
                        if (user == null || String.IsNullOrEmpty(user.objectId))
                        {
                            return(new BadRequestObjectResult(new ResponseContentModel
                            {
                                userMessage = "No such a user exist. Please check the Object Id",
                            }));
                        }
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "No such a user exist. Please check the Object Id",
                        }));
                    }

                    var status = await client.UpdateUser(data.ObjectId, JsonConvert.SerializeObject(new { givenName = data.FirstName, surname = data.LastName, displayName = data.DisplayName }));

                    if (status)
                    {
                        return((ActionResult) new OkObjectResult(status));
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, something happened unexpectedly. Couldn't update the user. Please try again later."
                        }));
                    }
                }
                else
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Please provide valid input"
                    }));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Sorry, something happened unexpectedly. Couldn't update the user. Please try again later.",
                    developerMessage = "See logging provider failure dependencies for exception information."
                }));
            }
        }
コード例 #24
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            try
            {
                log.LogInformation("Request started");
                string           requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                ChangeEmailModel data        = JsonConvert.DeserializeObject <ChangeEmailModel>(requestBody);
                log.LogInformation(requestBody);

                string         tenant       = _appSettings.B2CTenantId;                       // Environment.GetEnvironmentVariable("B2CTenantId", EnvironmentVariableTarget.Process);
                string         clientId     = _appSettings.B2CGraphAccessClientId.ToString(); // Environment.GetEnvironmentVariable("B2CGraphAccessClientId", EnvironmentVariableTarget.Process);
                string         clientSecret = _appSettings.B2CGraphAccessClientSecret;        // Environment.GetEnvironmentVariable("B2CGraphAccessClientSecret", EnvironmentVariableTarget.Process);
                B2CGraphClient client       = new B2CGraphClient(clientId, clientSecret, tenant);

                var newUser = await client.GetAllUsersAsync("$filter=signInNames/any(x:x/value eq '" + HttpUtility.UrlEncode(data.NewEmail) + "')");

                UserDetailsModel newUserDetails = JsonConvert.DeserializeObject <UserDetailsModel>(newUser);

                if (newUserDetails.value.Count > 0)
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Sorry, This email already exists",
                    }));
                }

                var currentUser = await client.GetUserByObjectId(data.ObjectId);

                if (!String.IsNullOrEmpty(currentUser))
                {
                    UserValueModel user = JsonConvert.DeserializeObject <UserValueModel>(currentUser);
                    log.LogInformation(currentUser);

                    if (user == null)
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, This user doesn't exists.",
                        }));
                    }

                    bool updateResult = false;

                    if (!data.IsResend)
                    {
                        var    extensionAppId = _appSettings.ExtensionAppId;// Environment.GetEnvironmentVariable("ExtensionAppId", EnvironmentVariableTarget.Process);
                        string json           = "{\"extension_" + extensionAppId + "_IsEmailChangeRequested\":\"true\",\"extension_" + extensionAppId + "_NewEmail\":\"" + data.NewEmail + "\"}";
                        try
                        {
                            updateResult = await client.UpdateUser(data.ObjectId, json);
                        }
                        catch (Exception)
                        {
                            return(new BadRequestObjectResult(new ResponseContentModel
                            {
                                userMessage = "Sorry, something happened unexpectedly while updating AD user.",
                            }));
                        }
                    }

                    if (updateResult || data.IsResend)
                    {
                        var accountActivationEmailExpiryInSeconds = _appSettings.AccountActivationEmailExpiryInSeconds;// Convert.ToInt32(Environment.GetEnvironmentVariable("AccountActivationEmailExpiryInSeconds", EnvironmentVariableTarget.Process));


                        string token = TokenBuilder.BuildIdToken(user.signInNames.FirstOrDefault().value, data.NewEmail, DateTime.UtcNow.AddSeconds(accountActivationEmailExpiryInSeconds), req.Scheme, req.Host.Value, req.PathBase.Value, data.ObjectId, "changeemail", _appSettings.ClientSigningKey, _appSettings.RelyingPartyAppClientId.ToString());

                        string b2cURL         = _appSettings.B2CAuthorizationUrl;                // Environment.GetEnvironmentVariable("B2CAuthorizationUrl", EnvironmentVariableTarget.Process);
                        string b2cTenant      = _appSettings.B2CTenant;                          // Environment.GetEnvironmentVariable("B2CTenant", EnvironmentVariableTarget.Process);
                        string b2cPolicyId    = _appSettings.B2CChangeEmailPolicy;               // Environment.GetEnvironmentVariable("B2CChangeEmailPolicy", EnvironmentVariableTarget.Process);
                        string b2cClientId    = _appSettings.RelyingPartyAppClientId.ToString(); // Environment.GetEnvironmentVariable("RelyingPartyAppClientId", EnvironmentVariableTarget.Process);
                        string b2cRedirectUri = _appSettings.B2CRedirectUri.ToString();          // Environment.GetEnvironmentVariable("B2CRedirectUri", EnvironmentVariableTarget.Process);
                        string url            = UrlBuilder.BuildUrl(token, b2cURL, b2cTenant, b2cPolicyId, b2cClientId, b2cRedirectUri);

                        string htmlTemplateOldEmail = _appSettings.NotifyEmailChangeConfirmationEmailOldEmailTemplateId.ToString(); // Environment.GetEnvironmentVariable("NotifyEmailChangeConfirmationEmailOldEmailTemplateId", EnvironmentVariableTarget.Process);
                        string htmlTemplateNewEmail = _appSettings.NotifyEmailChangeConfirmationEmailNewEmailTemplateId.ToString(); //Environment.GetEnvironmentVariable("NotifyEmailChangeConfirmationEmailNewEmailTemplateId", EnvironmentVariableTarget.Process);

                        bool       result2 = false;
                        EmailModel model   = new EmailModel
                        {
                            EmailTemplate   = htmlTemplateNewEmail,
                            To              = data.NewEmail.ToString(),
                            Personalisation = new Dictionary <string, dynamic>
                            {
                                { "name", user.givenName },
                                { "link", url }
                            }
                        };

                        var result1 = EmailService.Send(_appSettings.NotifyApiKey, model);

                        if (!data.IsResend)
                        {
                            model = new EmailModel
                            {
                                EmailTemplate   = htmlTemplateOldEmail,
                                To              = user.signInNames.FirstOrDefault().value,
                                Personalisation = new Dictionary <string, dynamic>
                                {
                                    { "name", user.givenName }
                                }
                            };

                            result2 = EmailService.Send(_appSettings.NotifyApiKey, model);
                        }
                        else
                        {
                            result2 = true;
                        }

                        if (result1 && result2 & data.SendTokenBackRequired)
                        {
                            return((ActionResult) new OkObjectResult(new { id_token_hint = token }));
                        }

                        return(result1 && result2
                            ? (ActionResult) new OkObjectResult(true)
                            : new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Failed to sent email, please contact support."
                        }));
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, Something happened unexpectedly. Please try after sometime."
                        }));
                    }
                }
                else
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Sorry, This user doesn't exists.",
                    }));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Sorry, Something happened unexpectedly. Please try after sometime.",
                    developerMessage = "See logging provider failure dependencies for exception information."
                }));
            }
        }
コード例 #25
0
        /// <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();
        }
        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());
        }
コード例 #27
0
ファイル: GraphUserManager.cs プロジェクト: sitesh1986/Azure
 public GraphUserManager(B2CGraphClient b2CGraphClient)
 {
     _b2CGraphClient = b2CGraphClient;
 }
コード例 #28
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "delete", Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {
                string id = req.Query["id"];
                log.LogInformation("Query: " + req.Query);
                log.LogInformation(id);
                if (!String.IsNullOrEmpty(id))
                {
                    string tenant       = _appSettings.B2CTenantId;                       // Environment.GetEnvironmentVariable("B2CTenantId", EnvironmentVariableTarget.Process);
                    string clientId     = _appSettings.B2CGraphAccessClientId.ToString(); // Environment.GetEnvironmentVariable("B2CGraphAccessClientId", EnvironmentVariableTarget.Process);
                    string clientSecret = _appSettings.B2CGraphAccessClientSecret;        // Environment.GetEnvironmentVariable("B2CGraphAccessClientSecret", EnvironmentVariableTarget.Process);

                    B2CGraphClient client = new B2CGraphClient(clientId, clientSecret, tenant);

                    var getUserApiResponse = await client.GetUserByObjectId(id);

                    if (!String.IsNullOrEmpty(getUserApiResponse))
                    {
                        var user = JsonConvert.DeserializeObject <UserValueModel>(getUserApiResponse);
                        if (user == null || String.IsNullOrEmpty(user.objectId))
                        {
                            return(new BadRequestObjectResult(new ResponseContentModel
                            {
                                userMessage = "No such a user exist. Please check the Object Id",
                            }));
                        }
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "No such a user exist. Please check the Object Id",
                        }));
                    }

                    var status = await client.DeleteUser(id);

                    if (status)
                    {
                        return((ActionResult) new OkObjectResult(status));
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, something happened unexpectedly. Couldn't delete the user. Please try again later."
                        }));
                    }
                }
                else
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Please pass object id of the user",
                    }));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Sorry, something happened unexpectedly. Couldn't delete the user. Please try again later.",
                    developerMessage = "See logging provider failure dependencies for exception information."
                }));
            }
        }
コード例 #29
0
 public HomeController(B2CGraphClient graphClient)
 {
     _graphClient = graphClient;
 }