AssignRolesRequest

We found 10 examples in language CSharp for this search. You will see 32 fragments of code.

Other methods


        /// <inheritdoc />
        public async Task RegisterPatient(string auth0UserId) =>
            await _managementApiClient.Users.AssignRolesAsync(auth0UserId,
                new AssignRolesRequest {Roles = new[] {PatientRoleId}});
        
        /// <inheritdoc />
        public async Task RegisterDoctor(string auth0UserId) =>
            await _managementApiClient.Users.AssignRolesAsync(auth0UserId,
                new AssignRolesRequest {Roles = new[] {UnverifiedDoctorRoleId}});

        /// <inheritdoc />
        public async Task MarkDoctorAsVerified(string auth0UserId)
        {
            await _managementApiClient.Users.RemoveRolesAsync(auth0UserId,
                new AssignRolesRequest {Roles = new[] {UnverifiedDoctorRoleId}});
            await _managementApiClient.Users.AssignRolesAsync(auth0UserId,
                new AssignRolesRequest {Roles = new[] {DoctorRoleId}});
        }


        public async Task AddUserRoleAsync(string? userId, string roleName)
        {
            if (string.IsNullOrEmpty(userId)) throw new ArgumentNullException("userId");

            var role = await GetRoleByName(roleName);

            string[] roles = { role.Id };

            await client.Users.AssignRolesAsync(userId, new AssignRolesRequest()
            {
                Roles = roles
            });
        }

        public async Task RemveUserRoleAsync(string? userId, string roleName)
        {
            if (string.IsNullOrEmpty(userId)) throw new ArgumentNullException("userId");

            var role = await GetRoleByName(roleName);

            string[] roles = { role.Id };

            await client.Users.RemoveRolesAsync(userId, new AssignRolesRequest()
            {
                Roles = roles
            });
        }

namespace Asam.Ppc.Service.Messages.Security
{
    using System.Collections.Generic;
    using Agatha.Common;

    public class AssignRolesRequest:Request
    {
        public long SystemAccoutnKey { get; set; }

        public bool AddRoles { get; set; }

        public IEnumerable<long> Roles { get; set; }
    }
}


        [HttpGet]
        public async Task<IEnumerable<UserDto.Index>> GetUsers()
        {
            var users = await _managementApiClient.Users.GetAllAsync(new GetUsersRequest(), new PaginationInfo());
            return users.Select(x => new UserDto.Index
            {
                Email = x.Email,
                FirstName = x.FirstName,
                LastName = x.LastName,
                Blocked = x.Blocked ?? false,
            });
        }

        [HttpPost]
        public async Task CreateUser(UserDto.Create user)
        {
            var createRequest = new UserCreateRequest
            {
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Password = user.Password,
                Connection = "Username-Password-Authentication",
            };
            var createdUser = await _managementApiClient.Users.CreateAsync(createRequest);

            var allRoles = await _managementApiClient.Roles.GetAllAsync(new GetRolesRequest());
            var adminRole = allRoles.First(x => x.Name == "Administrator");

            var assignRoleRequest = new AssignRolesRequest
            {
                Roles = new string[] { adminRole.Id }
            };
            await _managementApiClient.Users.AssignRolesAsync(createdUser?.UserId, assignRoleRequest);
        }


        public async Task GetManagementClientAccessToken(bool regenerate_if_exists = false)
        {
            if (!string.IsNullOrWhiteSpace(_client_access_token) && !regenerate_if_exists)
                return;

            if (!string.IsNullOrWhiteSpace(_options.TestingClientAccessToken))
            {
                _client_access_token = _options.TestingClientAccessToken;
            }
            else
            {
                var client = new AuthenticationApiClient(_options.ServerRootUrl);
                var tokenResponse = await client.GetTokenAsync(new ClientCredentialsTokenRequest
                {
                    ClientId = _options.ClientId,
                    ClientSecret = _options.ClientSecret,
                    Audience = _options.ApiIdentifier
                });
                _client_access_token = tokenResponse.AccessToken;
            }
        }

        public async Task LoadRoles()
        {
            if (_all_roles != null)
                return;

            var authManClient = new ManagementApiClient(_client_access_token, _options.ServerRootUrl, _managementConnection);
            _all_roles = await authManClient.Roles.GetAllAsync(new GetRolesRequest());
        }

        public async Task<User> GetUserInfo(string userId)
        {
            await this.GetManagementClientAccessToken();

            var authManClient = new ManagementApiClient(_client_access_token, _options.ServerRootUrl, _managementConnection);
            var userInfoResult = await authManClient.Users.GetAsync(userId);
            return userInfoResult;
        }

        public async Task AssignRolesToUser(string userId, string[] roles)
        {
            await this.GetManagementClientAccessToken();
            await this.LoadRoles();

            var authManClient = new ManagementApiClient(_client_access_token, _options.ServerRootUrl, _managementConnection);
            await authManClient.Users.AssignRolesAsync(userId, new AssignRolesRequest
            {
                Roles = _all_roles
                    .Where(x => roles.Contains(x.Name))
                    .Select(r => r.Id).ToArray()
            });
        }


        private void ClearApiTokenAsync()
        {
            _memoryCache.Remove(_CACHE_KEY);
        }

        private async Task<string> GetApiTokenAsync()
        {
            string encryptedToken = null;

            if (!_memoryCache.TryGetValue<string>(_CACHE_KEY, out encryptedToken))
            {
                string apiResponse = null;
                using (var client = new HttpClient())
                {
                    var encodedContent = new FormUrlEncodedContent(_tokenParameters);
                    using (var response = await client.PostAsync(_managementApiUrl, encodedContent))
                    {
                        apiResponse = await response.Content.ReadAsStringAsync();
                    }
                }
                JObject json = JObject.Parse(apiResponse);
                encryptedToken = Crypto.Encrypt(_auth0CryptoKey, (string)json["access_token"]);
                using (var entry = _memoryCache.CreateEntry(_CACHE_KEY))
                {
                    entry.Value = encryptedToken;
                    entry.AbsoluteExpiration = DateTime.UtcNow.AddDays(1);
                }
            }

            return Crypto.Decrypt(_auth0CryptoKey, encryptedToken);
        }

        public async Task<GetUserResponse> GetUserByEmailAsync(string email)
        {
            User user = null;
            var apiToken = await GetApiTokenAsync();
            var managementApiClient = new ManagementApiClient(apiToken, _domain);
            IList<Auth0.ManagementApi.Models.User> users = null;
            IPagedList<Auth0.ManagementApi.Models.Role> roles = null;

            try
            {
                users = await managementApiClient.Users.GetUsersByEmailAsync(email);
                if (users != null && users.Count() > 0)
                {
                    var auth0User = users.FirstOrDefault();
                    roles = await managementApiClient.Users.GetRolesAsync(auth0User.UserId, new PaginationInfo());

                    user = new User()
                    {
                        Email = auth0User.Email,
                        SubscriberGuid = auth0User.AppMetadata.subscriberGuid,
                        UserId = auth0User.UserId,
                        EmailVerified = auth0User.EmailVerified,
                        Roles = roles.Select(r =>
                            Enum.GetValues(typeof(Role))
                            .Cast<Role>()
                            .FirstOrDefault(x => x.GetDescription() == r.Name
                        )).ToList()
                    };
                }
                else
                {
                    return new GetUserResponse(false, "No user was found with that email address.", null);
                }

            }
            catch (ApiException ae)
            {
                if (ae.StatusCode == HttpStatusCode.Unauthorized)
                {
                    _logger.LogWarning($"An unauthorized Auth0 ApiException occurred in UserService.GetUserByEmailAsync (will refresh token and retry one time): {ae.Message}", ae);

                    try
                    {
                        // clear the token, get a new one, and try one more time
                        ClearApiTokenAsync();
                        apiToken = await GetApiTokenAsync();
                        managementApiClient = new ManagementApiClient(apiToken, _domain);
                        users = await managementApiClient.Users.GetUsersByEmailAsync(email);
                        if (users != null && users.Count() > 0)
                        {
                            var auth0User = users.FirstOrDefault();
                            roles = await managementApiClient.Users.GetRolesAsync(auth0User.UserId, new PaginationInfo());

                            user = new User()
                            {
                                Email = auth0User.Email,
                                SubscriberGuid = auth0User.AppMetadata.subscriberGuid,
                                UserId = auth0User.UserId,
                                EmailVerified = auth0User.EmailVerified,
                                Roles = roles.Select(r =>
                                    Enum.GetValues(typeof(Role))
                                    .Cast<Role>()
                                    .FirstOrDefault(x => x.GetDescription() == r.Name
                                )).ToList()
                            };
                        }
                        else
                        {
                            return new GetUserResponse(false, "No user was found with that email address.", null);
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogError($"An unexpected exception occurred in UserService.GetUserByEmailAsync (will not be retried): {e.Message}", e);
                        return new GetUserResponse(false, "An unexpected error has occured.", null);
                    }
                }
                else
                {
                    return new GetUserResponse(false, ae.Message, null);
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"An unexpected exception occurred in UserService.GetUserByEmailAsync (will not be retried): {e.Message}", e);
                return new GetUserResponse(false, "An unexpected error has occured.", null);
            }

            return new GetUserResponse(true, "User was retrieved successfully.", user);
        }

        public async Task<CreateUserResponse> CreateUserAsync(User user, bool requireEmailVerification, params Role[] userRoles)
        {
            // create an ADB2C account - this can be removed once WozU has switched to Auth0 for SSO (client id and secret)
            Guid subscriberGuid = Guid.NewGuid();
            try
            {
                var adb2cUser = await _graphClient.CreateUser(user.Email, user.Email, user.Password);
                subscriberGuid = Guid.Parse(adb2cUser.AdditionalData["objectId"].ToString());
            }
            catch (Exception e)
            {
                _logger.LogInformation($"An exception occurred while trying to create an ADB2C user: {e.Message}");
            }

            Auth0.ManagementApi.Models.User userCreationResponse = null;
            var subscriber = await _repositoryWrapper.SubscriberRepository.GetSubscriberByEmailAsync(user.Email);

            if (subscriber != null)
            {
                return new CreateUserResponse(false, "Email already in use.", null);
            }

            var apiToken = await GetApiTokenAsync();
            var managementApiClient = new ManagementApiClient(apiToken, _domain);

            UserCreateRequest userCreationRequest = new UserCreateRequest()
            {
                Email = user.Email,
                Connection = _CONNECTION_TYPE,
                Password = user.Password,
                VerifyEmail = requireEmailVerification,
                AppMetadata = new JObject()
            };

            userCreationRequest.AppMetadata.subscriberGuid = subscriberGuid;
            userCreationRequest.AppMetadata.acceptedTermsOfService = "October 16, 2018, version 1.0"; // may need to make this dynamic later
            userCreationRequest.AppMetadata.isOptInToMarketingEmails = user.IsAgreeToMarketingEmails;

            try
            {
                userCreationResponse = await managementApiClient.Users.CreateAsync(userCreationRequest);
            }
            catch (ApiException ae)
            {
                if (ae.StatusCode == HttpStatusCode.Unauthorized)
                {
                    _logger.LogWarning($"An unauthorized Auth0 ApiException occurred in UserService.CreateUserAsync (will refresh token and retry one time): {ae.Message}", ae);

                    try
                    {
                        // clear the token, get a new one, and try one more time
                        ClearApiTokenAsync();
                        apiToken = await GetApiTokenAsync();
                        managementApiClient = new ManagementApiClient(apiToken, _domain);
                        userCreationResponse = await managementApiClient.Users.CreateAsync(userCreationRequest);
                    }
                    catch (Exception e)
                    {
                        _logger.LogError($"An unexpected exception occurred in UserService.CreateUserAsync (will not be retried): {e.Message}", e);
                        return new CreateUserResponse(false, "An unexpected error has occured.", null);
                    }
                }
                else
                {
                    return new CreateUserResponse(false, ae.Message, null);
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"An unexpected exception occurred in UserService.CreateUserAsync (will not be retried): {e.Message}", e);
                return new CreateUserResponse(false, "An unexpected error has occured.", null);
            }

            user.UserId = userCreationResponse.UserId;
            user.SubscriberGuid = subscriberGuid;

            // todo: implement role assignment during user creation - potential security concerns here
            if (userRoles != null && userRoles.Length > 0)
                throw new NotImplementedException("Role assignment is not yet supported");

            return new CreateUserResponse(true, "Account has been created.", user);
        }

        public async Task<GetUsersResponse> GetUsersInRoleAsync(Role role)
        {
            var apiToken = await GetApiTokenAsync();
            var managementApiClient = new ManagementApiClient(apiToken, _domain);
            IPagedList<AssignedUser> assignedUsersInRole = null;
            try
            {
                var recruiterRoleIdLookup = await managementApiClient.Roles.GetAllAsync(new GetRolesRequest() { NameFilter = role.ToString() });
                assignedUsersInRole = await managementApiClient.Roles.GetUsersAsync(recruiterRoleIdLookup.FirstOrDefault().Id);
            }
            catch (ApiException ae)
            {
                _logger.LogWarning($"An Auth0 ApiException occurred in UserService.GetUsersInRoleAsync (will refresh token and retry one time): {ae.Message}", ae);
                if (ae.StatusCode == HttpStatusCode.Unauthorized)
                {
                    try
                    {
                        // clear the token, get a new one, and try one more time
                        ClearApiTokenAsync();
                        apiToken = await GetApiTokenAsync();
                        managementApiClient = new ManagementApiClient(apiToken, _domain);
                        var recruiterRoleIdLookup = await managementApiClient.Roles.GetAllAsync(new GetRolesRequest() { NameFilter = role.ToString() });
                        assignedUsersInRole = await managementApiClient.Roles.GetUsersAsync(recruiterRoleIdLookup.FirstOrDefault().Id);

                    }
                    catch (Exception e)
                    {
                        _logger.LogError($"An unexpected exception occurred in UserService.GetUsersInRoleAsync (will not be retried): {e.Message}", e);
                        return new GetUsersResponse(false, e.Message, null);
                    }
                }
                else
                {
                    _logger.LogError($"An unexpected exception occurred in UserService.GetUsersInRoleAsync (will not be retried): {ae.Message}", ae);
                    return new GetUsersResponse(false, ae.Message, null);
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"An unexpected exception occurred in UserService.GetUsersInRoleAsync (will not be retried): {e.Message}", e);
                return new GetUsersResponse(false, e.Message, null);
            }

            List<User> usersInRole = new List<User>();
            foreach (var assignedUserInRole in assignedUsersInRole)
            {
                usersInRole.Add(new User()
                {
                    Email = assignedUserInRole.Email,
                    UserId = assignedUserInRole.UserId,
                });
            }

            return new GetUsersResponse(true, $"Successfully retrieved users in role: {role.ToString()}", usersInRole);
        }

        public async Task<CreateUserResponse> MigrateUserAsync(User user)
        {
            Auth0.ManagementApi.Models.User userCreationResponse = null;
            var subscriber = await _repositoryWrapper.SubscriberRepository.GetSubscriberByEmailAsync(user.Email);

            if (subscriber == null)
            {
                return new CreateUserResponse(false, "The subscriber does not exist.", null);
            }
            else
            {
                var userGroupsFromADB2C = await _graphClient.GetUserGroupsByObjectId(subscriber.SubscriberGuid.Value.ToString());
                var adb2cAccount = await _graphClient.GetUserBySignInEmail(user.Email);
                string acceptedTermsOfService = string.Empty;
                bool isOptInToMarketingEmails = false;
                if (adb2cAccount.AdditionalData.Keys.Contains(_acceptedTermsOfServiceKeyName))
                    acceptedTermsOfService = adb2cAccount.AdditionalData[_acceptedTermsOfServiceKeyName].ToString();
                if (adb2cAccount.AdditionalData.Keys.Contains(_isOptInToMarketingEmailsKeyName))
                    isOptInToMarketingEmails = bool.Parse(adb2cAccount.AdditionalData[_isOptInToMarketingEmailsKeyName].ToString());
                var apiToken = await GetApiTokenAsync();
                var managementApiClient = new ManagementApiClient(apiToken, _domain);

                UserCreateRequest userCreationRequest = new UserCreateRequest()
                {
                    Email = user.Email,
                    Connection = _CONNECTION_TYPE,
                    Password = user.Password,
                    VerifyEmail = !subscriber.IsVerified,
                    AppMetadata = new JObject()
                };
                userCreationRequest.AppMetadata.subscriberGuid = subscriber.SubscriberGuid;
                userCreationRequest.AppMetadata.acceptedTermsOfService = acceptedTermsOfService;
                userCreationRequest.AppMetadata.isOptInToMarketingEmails = isOptInToMarketingEmails;

                try
                {
                    userCreationResponse = await managementApiClient.Users.CreateAsync(userCreationRequest);
                    if (subscriber.IsVerified)
                        await managementApiClient.Users.UpdateAsync(userCreationResponse.UserId, new UserUpdateRequest() { EmailVerified = true });
                    if (userGroupsFromADB2C != null && userGroupsFromADB2C.Count() > 0)
                    {
                        List<string> newRoles = new List<string>();
                        var auth0Roles = await managementApiClient.Roles.GetAllAsync(new GetRolesRequest() { NameFilter = null });
                        foreach (var oldGroup in userGroupsFromADB2C)
                        {
                            var matchingRole = auth0Roles.Where(r => r.Name == oldGroup.DisplayName).FirstOrDefault();
                            if (matchingRole != null)
                                newRoles.Add(matchingRole.Id);
                        }
                        if (newRoles.Count() > 0)
                            await managementApiClient.Users.AssignRolesAsync(userCreationResponse.UserId, new AssignRolesRequest() { Roles = newRoles.ToArray() });
                    }

                    // cannot do this because we need the person to be active for WozU
                    // _graphClient.DisableUser(user.SubscriberGuid);

                    subscriber.Auth0UserId = userCreationResponse.UserId;
                    subscriber.ModifyDate = DateTime.UtcNow;
                    subscriber.ModifyGuid = Guid.Empty;
                    await _repositoryWrapper.SubscriberRepository.SaveAsync();

                }
                catch (ApiException ae)
                {
                    if (ae.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        _logger.LogWarning($"An unauthorized Auth0 ApiException occurred in UserService.MigrateUserAsync (will refresh token and retry one time): {ae.Message}", ae);

                        try
                        {
                            // clear the token, get a new one, and try one more time
                            ClearApiTokenAsync();
                            apiToken = await GetApiTokenAsync();
                            managementApiClient = new ManagementApiClient(apiToken, _domain);
                            userCreationResponse = await managementApiClient.Users.CreateAsync(userCreationRequest);
                            if (subscriber.IsVerified)
                                await managementApiClient.Users.UpdateAsync(userCreationResponse.UserId, new UserUpdateRequest() { EmailVerified = true });
                            if (userGroupsFromADB2C != null && userGroupsFromADB2C.Count() > 0)
                            {
                                List<string> newRoles = new List<string>();
                                var auth0Roles = await managementApiClient.Roles.GetAllAsync(new GetRolesRequest() { NameFilter = null });
                                foreach (var oldGroup in userGroupsFromADB2C)
                                {
                                    var matchingRole = auth0Roles.Where(r => r.Name == oldGroup.DisplayName).FirstOrDefault();
                                    if (matchingRole != null)
                                        newRoles.Add(matchingRole.Id);
                                }
                                if (newRoles.Count() > 0)
                                    await managementApiClient.Users.AssignRolesAsync(userCreationResponse.UserId, new AssignRolesRequest() { Roles = newRoles.ToArray() });
                            }
                            await _graphClient.DisableUser(user.SubscriberGuid);

                            subscriber.Auth0UserId = userCreationResponse.UserId;
                            subscriber.ModifyDate = DateTime.UtcNow;
                            subscriber.ModifyGuid = Guid.Empty;
                            await _repositoryWrapper.SubscriberRepository.SaveAsync();
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"An unexpected exception occurred in UserService.MigrateUserAsync (will not be retried): {e.Message}", e);
                            return new CreateUserResponse(false, "An unexpected error has occured.", null);
                        }
                    }
                    else
                    {
                        _logger.LogError($"An exception occurred in UserService.MigrateUserAsync (will not be retried): {ae.Message}", ae);
                        return new CreateUserResponse(false, ae.Message, null);
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError($"An unexpected exception occurred in UserService.MigrateUserAsync (will not be retried): {e.Message}", e);
                    return new CreateUserResponse(false, "An unexpected error has occured.", null);
                }

                user.UserId = userCreationResponse.UserId;
                user.SubscriberGuid = userCreationResponse.AppMetadata.subscriberGuid;

                return new CreateUserResponse(true, "User has been migrated successfully.", user);
            }
        }


        [Authorize(Policy = "read:admin")]
        [HttpGet("users")]
        public async Task<IActionResult> GetAllUser([FromQuery] int from = 0, [FromQuery] int take = 50)
        {
            try
            {
                var users = await _apiClient.Users.GetAllAsync(new GetUsersRequest(), new PaginationInfo(from, take));

                return Ok(users.Select(user =>
                {
                    return new
                    {
                        position = from++,
                        email = user.Email,
                        fullName = user.FullName,
                        isBlocked = user.Blocked,
                        userId = user.UserId
                    };
                }));
            }
            catch (ErrorApiException e)
            {
                Log.Error(e, "Admin - GetAllUser");
                return BadRequest(e.Message);
            }
        }

        [Authorize(Policy = "read:admin")]
        [HttpGet("users/{id}")]
        public async Task<IActionResult> GetUser(string id)
        {
            try
            {
                var user = await _apiClient.Users.GetAsync(id);
                return Ok(
                     new
                     {
                         email = user.Email,
                         fullName = user.FullName,
                         isBlocked = user.Blocked,
                         userId = user.UserId
                     }
                );
            }
            catch (ErrorApiException e)
            {
                Log.Error(e, "Admin - GetUser");
                return BadRequest(e.Message);
            }
        }

        [Authorize(Policy = "read:admin")]
        [HttpGet("users/{id}/roles")]
        public async Task<IActionResult> GetUserRoles(string id, [FromQuery] int from = 0, [FromQuery] int take = 50)
        {
            try
            {
                var roles = await _apiClient.Users.GetRolesAsync(id, new PaginationInfo(from, take));
                return Ok(roles);
            }
            catch (ErrorApiException e)
            {
                Log.Error(e, "Admin - AddRoleToUsers");
                return BadRequest(e.Message);
            }
        }

        [Authorize(Policy = "write:admin")]
        [HttpPost("users/{id}/roles")]
        public async Task<IActionResult> AddRoleToUsers(string id, [FromBody] IdsDto dto)
        {
            try
            {
                await _apiClient.Users.AssignRolesAsync(id, new AssignRolesRequest { Roles = dto.Ids });
                return Ok();
            }
            catch (ErrorApiException e)
            {
                Log.Error(e, "Admin - AddRoleToUsers");
                return BadRequest(e.Message);
            }
        }

        [Authorize(Policy = "write:admin")]
        [HttpPost("users/{id}/roles/removes")]
        public async Task<IActionResult> RemoveRoleFromUsers(string id, [FromBody] IdsDto dto)
        {
            try
            {
                await _apiClient.Users.RemoveRolesAsync(id, new AssignRolesRequest { Roles = dto.Ids });
                return Ok();
            }
            catch (ErrorApiException e)
            {
                Log.Error(e, "Admin - RemoveRoleFromUsers");
                return BadRequest(e.Message);
            }
        }

        [Authorize(Policy = "read:admin")]
        [HttpGet("roles")]
        public async Task<IActionResult> GetAllRoles()
        {
            try
            {
                var roles = await _apiClient.Roles.GetAllAsync(new GetRolesRequest());
                return Ok(roles);
            }
            catch (ErrorApiException e)
            {
                Log.Error(e, "Admin - GetAllRoles");
                return BadRequest(e.Message);
            }
        }

using Newtonsoft.Json;

namespace Auth0.ManagementApi.Models
{
    /// <summary>
    /// Contains details of roles that should be assigned to a user.
    /// </summary>
    public class AssignRolesRequest
    {
        /// <summary>
        /// Role IDs to assign to the user.
        /// </summary>
        [JsonProperty("roles")]
        public string[] Roles { get; set; }
    }
}

#region License Header

// /*******************************************************************************
//  * Open Behavioral Health Information Technology Architecture (OBHITA.org)
//  * 
//  * Redistribution and use in source and binary forms, with or without
//  * modification, are permitted provided that the following conditions are met:
//  *     * Redistributions of source code must retain the above copyright
//  *       notice, this list of conditions and the following disclaimer.
//  *     * Redistributions in binary form must reproduce the above copyright
//  *       notice, this list of conditions and the following disclaimer in the
//  *       documentation and/or other materials provided with the distribution.
//  *     * Neither the name of the <organization> nor the
//  *       names of its contributors may be used to endorse or promote products
//  *       derived from this software without specific prior written permission.
//  * 
//  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
//  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//  ******************************************************************************/

#endregion

namespace ProCenter.Service.Message.Security
{
    #region Using Statements

    using System;
    using System.Collections.Generic;

    using Agatha.Common;

    #endregion

    /// <summary>The assign roles request class.</summary>
    public class AssignRolesRequest : Request
    {
        #region Public Properties

        /// <summary>
        /// Gets or sets a value indicating whether [add roles].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [add roles]; otherwise, <c>false</c>.
        /// </value>
        public bool AddRoles { get; set; }

        /// <summary>
        /// Gets or sets the roles.
        /// </summary>
        /// <value>
        /// The roles.
        /// </value>
        public IEnumerable<Guid> Roles { get; set; }

        /// <summary>
        /// Gets or sets the system accoutn key.
        /// </summary>
        /// <value>
        /// The system accoutn key.
        /// </value>
        public Guid SystemAccoutnKey { get; set; }

        #endregion
    }
}


        public async Task InitializeAsync()
        {
            string token = await GenerateManagementApiToken();

            _apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"), new HttpClientManagementConnection(options: new HttpClientManagementConnectionOptions { NumberOfHttpRetries = 9 }));

            // We will need a connection to add the roles to...
            _connection = await _apiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name = "Temp-Int-Test-" + MakeRandomName(),
                Strategy = "auth0",
                EnabledClients = new[] {GetVariable("AUTH0_CLIENT_ID"), GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID")}
            });
        }

        public async Task DisposeAsync()
        {
            await _apiClient.Connections.DeleteAsync(_connection.Id);
            _apiClient.Dispose();
        }

        [Fact]
        public async Task Test_roles_crud_sequence()
        {
            // Add a new role
            var newRoleRequest = new RoleCreateRequest
            {
                Name = $"{Guid.NewGuid():N}role",
                Description = $"{Guid.NewGuid():N}description",
            };
            var newRoleResponse = await _apiClient.Roles.CreateAsync(newRoleRequest);
            newRoleResponse.Should().NotBeNull();
            newRoleResponse.Name.Should().Be(newRoleRequest.Name);
            newRoleResponse.Description.Should().Be(newRoleRequest.Description);

            // Update the role
            var updateRoleRequest = new RoleUpdateRequest
            {
                Name = $"{Guid.NewGuid():N}role",
            };
            var updateRoleResponse = await _apiClient.Roles.UpdateAsync(newRoleResponse.Id, updateRoleRequest);
            updateRoleResponse.Should().NotBeNull();
            updateRoleResponse.Name.Should().Be(updateRoleRequest.Name);

            // Get a single role
            var role = await _apiClient.Roles.GetAsync(newRoleResponse.Id);
            role.Should().NotBeNull();
            role.Name.Should().Be(updateRoleResponse.Name);

            // Create a user
            var newUserRequest = new UserCreateRequest
            {
                Connection = _connection.Name,
                Email = $"{Guid.NewGuid():N}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password = Password
            };
            var user = await _apiClient.Users.CreateAsync(newUserRequest);

            // Assign a user to the role
            var assignUsersRequest = new AssignUsersRequest
            {
                Users = new[]
                {
                    user.UserId
                }
            };
            await _apiClient.Roles.AssignUsersAsync(role.Id, assignUsersRequest);

            // Ensure the user is assigned to the role
            var assignedUsers = await _apiClient.Roles.GetUsersAsync(role.Id);
            assignedUsers.Should().NotBeNull();
            assignedUsers.First().UserId.Should().Be(user.UserId);

            // Ensure the Role is assigned to user
            var assignedRoles = await _apiClient.Users.GetRolesAsync(user.UserId, new PaginationInfo());
            assignedRoles.Should().NotBeNull();
            assignedRoles.First().Id.Should().Be(role.Id);

            // Delete the role and ensure we get an exception when trying to fetch them again
            await _apiClient.Roles.DeleteAsync(role.Id);
            Func<Task> getFunc = async () => await _apiClient.Roles.GetAsync(role.Id);
            getFunc.Should().Throw<ErrorApiException>().And.ApiError.Error.Should().Be("Not Found");

            // Delete the user
            await _apiClient.Users.DeleteAsync(user.UserId);
        }

        [Fact]
        public async Task Test_roles_assign_user_to_role()
        {
            // Add a new role
            var newRoleRequest = new RoleCreateRequest
            {
                Name = $"{Guid.NewGuid():N}role",
                Description = $"{Guid.NewGuid():N}description",
            };
            var role = await _apiClient.Roles.CreateAsync(newRoleRequest);
            role.Should().NotBeNull();
            role.Name.Should().Be(newRoleRequest.Name);
            role.Description.Should().Be(newRoleRequest.Description);

            // Create a user
            var newUserRequest = new UserCreateRequest
            {
                Connection = _connection.Name,
                Email = $"{Guid.NewGuid():N}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password = Password
            };
            var user = await _apiClient.Users.CreateAsync(newUserRequest);

            // Assign a user to the role
            var assignUsersRequest = new AssignUsersRequest
            {
                Users = new[]
                {
                    user.UserId
                }
            };
            await _apiClient.Roles.AssignUsersAsync(role.Id, assignUsersRequest);

            // Ensure the user is assigned to the role
            var assignedUsers = await _apiClient.Roles.GetUsersAsync(role.Id);
            assignedUsers.Should().NotBeNull();
            assignedUsers.First().UserId.Should().Be(user.UserId);

            // Clean Up
            await _apiClient.Roles.DeleteAsync(role.Id);
            await _apiClient.Users.DeleteAsync(user.UserId);
        }

        [Fact]
        public async Task Test_roles_assign_role_to_user()
        {
            // Add a new role
            var newRoleRequest = new RoleCreateRequest
            {
                Name = $"{Guid.NewGuid():N}role",
                Description = $"{Guid.NewGuid():N}description",
            };
            var role = await _apiClient.Roles.CreateAsync(newRoleRequest);
            role.Should().NotBeNull();
            role.Name.Should().Be(newRoleRequest.Name);
            role.Description.Should().Be(newRoleRequest.Description);

            // Create a user
            var newUserRequest = new UserCreateRequest
            {
                Connection = _connection.Name,
                Email = $"{Guid.NewGuid():N}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password = Password
            };
            var user = await _apiClient.Users.CreateAsync(newUserRequest);

            // Assign a user to the role
            var assignRolesRequest = new AssignRolesRequest()
            {
                Roles = new[]
                {
                    role.Id
                }
            };
            await _apiClient.Users.AssignRolesAsync(user.UserId, assignRolesRequest);

            // Ensure the Role is assigned to user
            var assignedRoles = await _apiClient.Users.GetRolesAsync(user.UserId, new PaginationInfo());
            assignedRoles.Should().NotBeNull();
            assignedRoles.Should().HaveCount(1);
            assignedRoles.First().Id.Should().Be(role.Id);

            // Remove role from user
            await _apiClient.Users.RemoveRolesAsync(user.UserId, assignRolesRequest);

            // Ensure the Role has been removed from user
            var removedRoles = await _apiClient.Users.GetRolesAsync(user.UserId, new PaginationInfo());
            removedRoles.Should().NotBeNull();
            removedRoles.Should().HaveCount(0);

            // Clean Up
            await _apiClient.Roles.DeleteAsync(role.Id);
            await _apiClient.Users.DeleteAsync(user.UserId);
        }

        [Fact]
        public async Task Test_roles_assign_unassign_permission_to_role()
        {
            // Add a new role
            var newRoleRequest = new RoleCreateRequest
            {
                Name = $"{Guid.NewGuid():N}role",
                Description = $"{Guid.NewGuid():N}description",
            };
            var role = await _apiClient.Roles.CreateAsync(newRoleRequest);
            role.Should().NotBeNull();
            role.Name.Should().Be(newRoleRequest.Name);
            role.Description.Should().Be(newRoleRequest.Description);

            // Get a resource server
            var resourceServer = await _apiClient.ResourceServers.GetAsync("dotnet-testing");
            var originalScopes = resourceServer.Scopes != null ? resourceServer.Scopes.ToList() : new List<ResourceServerScope>();

            // Create a permission/scope
            var newScope = new ResourceServerScope { Value = $"{Guid.NewGuid():N}scope", Description = "Integration test" };

            // Update resource server with new scope
            resourceServer = await _apiClient.ResourceServers.UpdateAsync(resourceServer.Id, new ResourceServerUpdateRequest
            {
                Scopes = originalScopes.Concat(new[] { newScope }).ToList(),
            });

            // Associate a permission with the role
            var assignPermissionsRequest = new AssignPermissionsRequest()
            {
                Permissions = new[] { new PermissionIdentity { Identifier = resourceServer.Identifier, Name = newScope.Value } } 
            };
            await _apiClient.Roles.AssignPermissionsAsync(role.Id, assignPermissionsRequest);

            // Ensure the permission is associated with the role
            var associatedPermissions = await _apiClient.Roles.GetPermissionsAsync(role.Id, new PaginationInfo());
            associatedPermissions.Should().NotBeNull();
            associatedPermissions.Should().HaveCount(1);
            associatedPermissions.First().Identifier.Should().Be(resourceServer.Identifier);
            associatedPermissions.First().Name.Should().Be(newScope.Value);

            // Unassociate a permission with the role
            await _apiClient.Roles.RemovePermissionsAsync(role.Id, assignPermissionsRequest);

            // Ensure the permission is unassociated with the role
            associatedPermissions = await _apiClient.Roles.GetPermissionsAsync(role.Id, new PaginationInfo());
            associatedPermissions.Should().NotBeNull();
            associatedPermissions.Should().HaveCount(0);

            // Clean Up - Remove the permission from the resource server
            await _apiClient.ResourceServers.UpdateAsync(resourceServer.Id, new ResourceServerUpdateRequest
            {
                Scopes = originalScopes
            });

            // Clean Up - Remove the role
            await _apiClient.Roles.DeleteAsync(role.Id);
        }

Auth0.ManagementApi.Models.AssignRolesRequest : Object

Constructors :

public AssignRolesRequest()

Methods :

public String[] get_Roles()
public Void set_Roles(String[] value = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods