public async Task AddUserToGroupAsync(User user, Group group) { var body = new CustomDirectoryObject { ObjectDataId = $"{_graphApiSettings.GraphApiBaseUri}v1.0/{_graphApiSettings.TenantId}/directoryObjects/{user.Id}" }; var stringContent = new StringContent(JsonConvert.SerializeObject(body)); var accessUri = $"{_graphApiSettings.GraphApiBaseUri}v1.0/{_graphApiSettings.TenantId}/groups/{group.Id}/members/$ref"; var responseMessage = await _secureHttpRequest.PostAsync(_graphApiSettings.AccessToken, stringContent, accessUri); if (responseMessage.IsSuccessStatusCode) { return; } var reason = await responseMessage.Content.ReadAsStringAsync(); // if we failed because the user is already in the group, consider it done anyway if (reason.Contains("already exist")) { return; } var message = $"Failed to add user {user.Id} to group {group.Id}"; throw new UserServiceException(message, reason); }
public async Task <NewAdUserAccount> CreateUserAsync(string username, string firstName, string lastName, string displayName, string recoveryEmail, bool isTestUser = false) { // the user object provided by the graph api nuget package is missing the otherMails property // but it's there in the API so using a dynamic request model instead var newPassword = isTestUser ? _testDefaultPassword : _passwordService.GenerateRandomPasswordWithDefaultComplexity(); var user = new { displayName, givenName = firstName, surname = lastName, mailNickname = $"{firstName}.{lastName}".ToLower(), otherMails = new List <string> { recoveryEmail }, accountEnabled = true, userPrincipalName = username, passwordProfile = new { forceChangePasswordNextSignIn = !isTestUser, password = newPassword } }; var json = JsonConvert.SerializeObject(user); var stringContent = new StringContent(json); var accessUri = $"{_baseUrl}/users"; var response = await _secureHttpRequest.PostAsync(_graphApiSettings.AccessToken, stringContent, accessUri); await AssertResponseIsSuccessful(response); var responseJson = await response.Content.ReadAsStringAsync(); var adAccount = JsonConvert.DeserializeObject <User>(responseJson); return(new NewAdUserAccount { OneTimePassword = newPassword, UserId = adAccount.Id, Username = adAccount.UserPrincipalName }); }