Beispiel #1
0
        public async Task DeleteAsync(FlightUser flightUser)
        {
            if (HasAccessToken(out string token))
            {
                var accessToken = JsonConvert.DeserializeObject <JsonAccessToken>(token);
                var client      = new ManagementApiClient(accessToken.access_token, AppServices.Auth0Settings["Domain"]);
                var user        = ReadByEmailAsync(flightUser.Email).Result;

                if (user == null)
                {
                    return;
                }
                else
                {
                    var userUpdateRequest = new UserUpdateRequest()
                    {
                        Connection = AppServices.Auth0Settings["Connection"],
                        ClientId   = AppServices.Auth0Settings["ManagementClientId"],

                        Blocked = true
                    };

                    await client.Users.UpdateAsync(user.UserId, userUpdateRequest);
                }
            }
            else
            {
                return;
            }
        }
Beispiel #2
0
        public static async Task ManagementApiMainAsync(string[] args)
        {
            string token = "";

            var api = new ManagementApiClient(token, "jerrie.auth0.com");

            ClientCreateRequest clientCreateRequest = new ClientCreateRequest()
            {
                Name            = "Test name",
                ApplicationType = ClientApplicationType.NonInteractive,
                ResourceServers = new[]
                {
                    new ClientResourceServerAssociation
                    {
                        Identifier = "urn:test-api",
                        Scopes     = new[] { "read:appointments", "create:appointments" }
                    }
                },
                JwtConfiguration = new JwtConfiguration
                {
                    SigningAlgorithm  = "RS256",
                    LifetimeInSeconds = 3600
                }
            };
            await api.Clients.CreateAsync(clientCreateRequest);
        }
        public async Task InitializeAsync()
        {
            string token = await GenerateManagementApiToken();

            _managementApiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"));

            // We will need a connection to add the users to...
            _connection = await _managementApiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name           = Guid.NewGuid().ToString("N"),
                Strategy       = "auth0",
                EnabledClients = new[] { GetVariable("AUTH0_CLIENT_ID"), GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID") }
            });

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

            _newUser = await _managementApiClient.Users.CreateAsync(newUserRequest);

            _authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));
        }
Beispiel #4
0
        public async Task SetUp()
        {
            var scopes = new
            {
                users = new
                {
                    actions = new string[] { "create", "delete" }
                },
                connections = new
                {
                    actions = new string[] { "create", "delete" }
                }
            };
            string token = GenerateToken(scopes);

            managementApiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // We will need a connection to add the users to...
            connection = await managementApiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name           = Guid.NewGuid().ToString("N"),
                Strategy       = "auth0",
                EnabledClients = new[] { clientId }
            });
        }
Beispiel #5
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="managementClient">Auth0 用户管理API Client实例</param>
 /// <param name="dataContext">用户数据的数据库上下文</param>
 /// <param name="configuration">程序配置文件</param>
 /// <param name="roleGetter">可用用户身份获取服务接口</param>
 public UserManagementService(ManagementApiClient managementClient, UserDataContext dataContext, IConfiguration configuration, IAvailableRoleGetterService roleGetter)
 {
     this.dataContext   = dataContext;
     this.configuration = configuration;
     this.roleGetter    = roleGetter;
     userClient         = managementClient.Users;
 }
Beispiel #6
0
        private static async void MainAsync(string[] args)
        {
            var apiClient = new ManagementApiClient(ConfigurationManager.AppSettings["ApiToken"], new Uri(ConfigurationManager.AppSettings["ApiBaseUrl"]));

            // Test client methods
            //await TestClientMethods(apiClient);

            // Test connection methods
            //await TestConnectionMethods(apiClient);

            // Test device credentials
            //await TestDeviceCredentialsMethods(apiClient);

            // Test rules
            //await TestRuleMethods(apiClient);

            // Test users
            //await TestUserMethods(apiClient);

            // Test user account linking
            //await TestUserAccountLinkMethods(apiClient);

            // Test emails
            //await TestEmailsMethods(apiClient);

            // Test jobs
            //await TestJobsMethods(apiClient);

            // Test stats
            //await TestStatsMethods(apiClient);

            // Test tickets
            //await TestTicketsMethods(apiClient);
        }
Beispiel #7
0
        public async Task SetUp()
        {
            var scopes = new
            {
                users = new
                {
                    actions = new string[] { "read", "create", "update", "delete" }
                },
                connections = new
                {
                    actions = new string[] { "create", "delete" }
                },
                users_app_metadata = new
                {
                    actions = new string[] { "update" }
                },
                logs = new
                {
                    actions = new string[] { "read" }
                }
            };
            string token = GenerateToken(scopes);

            apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // We will need a connection to add the users to...
            connection = await apiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name           = Guid.NewGuid().ToString("N"),
                Strategy       = "auth0",
                EnabledClients = new[] { "rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW" }
            });
        }
        public ManagementApiClientTests()
        {
            management = new ManagementApiClient("fake", GetVariable("AUTH0_MANAGEMENT_API_URL"), grabber);

            management.TenantSettings.GetAsync(); // Cause headers to be "sent" to the grabber for testing
            payload = JObject.Parse(Encoding.ASCII.GetString(Utils.Base64UrlDecode(grabber.LastHeaders["Auth0-Client"])));
        }
Beispiel #9
0
        public async Task SetUp()
        {
            var scopes = new
            {
                users = new
                {
                    actions = new string[] { "create", "delete", "update" }
                },
                connections = new
                {
                    actions = new string[] { "create", "delete" }
                }
            };
            string token = GenerateToken(scopes);

            apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Create a connection
            connection = await apiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name           = Guid.NewGuid().ToString("N"),
                Strategy       = "auth0",
                EnabledClients = new[] { "rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW" }
            });

            // Create a user
            user = await apiClient.Users.CreateAsync(new UserCreateRequest
            {
                Connection    = connection.Name,
                Email         = $"{Guid.NewGuid().ToString("N")}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password      = "******"
            });
        }
Beispiel #10
0
        public async Task SetUp()
        {
            var scopes = new
            {
                users = new
                {
                    actions = new string[] { "create", "delete", "update" }
                },
                connections = new
                {
                    actions = new string[] { "create", "delete" }
                }
            };
            string token = GenerateToken(scopes);

            apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Create a connection
            connection = await apiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name = Guid.NewGuid().ToString("N"),
                Strategy = "auth0",
                EnabledClients = new[] { "rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW" }
            });

            // Create a user
            user = await apiClient.Users.CreateAsync(new UserCreateRequest
            {
                Connection = connection.Name,
                Email = $"{Guid.NewGuid().ToString("N")}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password = "******"
            });
        }
Beispiel #11
0
        private static async Task TestUserMethods(ManagementApiClient apiClient)
        {
            // Create a new user
            //var newUserRequest = new UserCreateRequest
            //{
            //    Connection = "Username-Password-Authentication",
            //    Email = "*****@*****.**",
            //    EmailVerified = true,
            //    Password = "******"
            //};
            //var newUser = await apiClient.Users.Create(newUserRequest);

            // Get a single user
            //var user = await apiClient.Users.Get(newUser.UserId);

            // Get all users
            //var users = await apiClient.Users.GetAll();

            // Update the user
            //var updateUserRequest = new UserUpdateRequest
            //{
            //    Email = "*****@*****.**",
            //    VerifyEmail = false
            //};
            //var updatedUser = await apiClient.Users.Update(newUser.UserId, updateUserRequest);

            // Delete the user
            //await apiClient.Users.Delete(newUser.UserId);

            // Delete all users
            //await apiClient.Users.DeleteAll();
        }
Beispiel #12
0
        public IActionResult NewUser([FromBody] NewUser user)
        {
            if (ModelState.IsValid)
            {
                switch (ds.AddNewUser(user, Convert.ToInt32(GetSchoolIdForCurrentUser())))
                {
                case ObjectManipulationResult.Success:
                    using (var managementClient = new ManagementApiClient())
                    {
                        var userAuth0 = managementClient.CreateUser(user);
                        if (userAuth0 != null)
                        {
                            managementClient.RequestVerifyEmail(userAuth0?.UserId);
                        }
                    }
                    return(StatusCode(200, "New user created successfully"));

                case ObjectManipulationResult.Exists:
                    return(StatusCode(409, "User exists"));

                case ObjectManipulationResult.ErrorOccured:
                    return(StatusCode(503, "Error occured"));

                default:
                    return(StatusCode(503, "Error occured"));
                }
            }

            return(StatusCode(400, "Model is not valid"));
        }
Beispiel #13
0
        private static async Task TestRuleMethods(ManagementApiClient apiClient)
        {
            // Create a new rule
            var newRuleRequest = new RuleCreateRequest
            {
                Name   = "New rule",
                Script = @"function (user, context, callback) {
                              // TODO: implement your rule
                              callback(null, user, context);
                            }"
            };
            var newRule = await apiClient.Rules.CreateAsync(newRuleRequest);

            // Get a single rule
            var rule = await apiClient.Rules.GetAsync(newRule.Id);

            // Get all rules
            var rules = await apiClient.Rules.GetAllAsync();

            // Update a rule
            var updateRuleRequest = new RuleUpdateRequest
            {
                Name = "Updated rule"
            };
            var updatedRule = await apiClient.Rules.UpdateAsync(newRule.Id, updateRuleRequest);

            // Delete a rule
            await apiClient.Rules.DeleteAsync(newRule.Id);
        }
Beispiel #14
0
        public async Task Test_device_credentials_crud_sequence()
        {
            var apiClient = new ManagementApiClient(GetVariable("AUTH0_TOKEN_DEVICE_CREDENTIALS"), new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            //Get all the device credentials
            var credentialsBefore = await apiClient.DeviceCredentials.GetAllAsync();

            //Create a new device credential
            var newCredentialRequest = new DeviceCredentialCreateRequest
            {
                DeviceName = Guid.NewGuid().ToString("N"),
                DeviceId   = Guid.NewGuid().ToString("N"),
                ClientId   = client.ClientId,
                Type       = "public_key",
                Value      = "new-key-value"
            };
            var newCredentialResponse = await apiClient.DeviceCredentials.CreateAsync(newCredentialRequest);

            newCredentialResponse.Should().NotBeNull();
            newCredentialResponse.DeviceId.Should().Be(newCredentialRequest.DeviceId);
            newCredentialResponse.DeviceName.Should().Be(newCredentialRequest.DeviceName);

            // Check that we now have one more device credential
            var credentialsAfterCreate = await apiClient.DeviceCredentials.GetAllAsync();

            credentialsAfterCreate.Count.Should().Be(credentialsBefore.Count + 1);

            // Delete the device credential
            await apiClient.DeviceCredentials.DeleteAsync(newCredentialResponse.Id);

            // Check that we now have one less device credential
            var credentialsAfterDelete = await apiClient.DeviceCredentials.GetAllAsync();

            credentialsAfterDelete.Count.Should().Be(credentialsAfterCreate.Count - 1);
        }
Beispiel #15
0
        public async Task InitializeAsync()
        {
            string token = await GenerateManagementApiToken();

            _apiClient = new TestManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"));

            _authConnection = 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") }
            });

            _emailConnection = await _apiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name           = "Temp-Int-Test-" + MakeRandomName(),
                Strategy       = "email",
                EnabledClients = new[] { GetVariable("AUTH0_CLIENT_ID"), GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID") }
            });

            _auth0User = await _apiClient.Users.CreateAsync(new UserCreateRequest
            {
                Connection    = _authConnection.Name,
                Email         = $"{Guid.NewGuid():N}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password      = Password
            });

            _emailUser = await _apiClient.Users.CreateAsync(new UserCreateRequest
            {
                Connection    = _emailConnection.Name,
                Email         = $"{Guid.NewGuid():N}@nonexistingdomain.aaa",
                EmailVerified = true,
            });
        }
Beispiel #16
0
        private static async Task TestEmailsMethods(ManagementApiClient apiClient)
        {
            // Get the email provider
            var provider = await apiClient.EmailProvider.GetAsync("name,enabled,credentials,settings");

            // Delete the email provider
            await apiClient.EmailProvider.DeleteAsync();

            // Configure the email provider
            var configureRequest = new EmailProviderConfigureRequest
            {
                Name        = "mandrill",
                IsEnabled   = true,
                Credentials = new EmailProviderCredentials
                {
                    ApiKey = "ABC"
                }
            };
            var configureResponse = await apiClient.EmailProvider.ConfigureAsync(configureRequest);

            // Update the email provider
            var updateRequest = new EmailProviderUpdateRequest
            {
                Name        = "mandrill",
                IsEnabled   = true,
                Credentials = new EmailProviderCredentials
                {
                    ApiKey = "XYZ"
                }
            };
            var updateResponse = await apiClient.EmailProvider.UpdateAsync(updateRequest);
        }
Beispiel #17
0
        public async Task InitializeAsync()
        {
            var apiClient = new ManagementApiClient(GetVariable("AUTH0_TOKEN_DEVICE_CREDENTIALS"), GetVariable("AUTH0_MANAGEMENT_API_URL"));

            // Set up the correct Client, Connection and User
            _client = await apiClient.Clients.CreateAsync(new ClientCreateRequest
            {
                Name = Guid.NewGuid().ToString("N")
            });

            _connection = await apiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name           = Guid.NewGuid().ToString("N"),
                Strategy       = "auth0",
                EnabledClients = new[] { _client.ClientId }
            });

            _user = await apiClient.Users.CreateAsync(new UserCreateRequest
            {
                Connection    = _connection.Name,
                Email         = $"{Guid.NewGuid():N}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password      = Password
            });
        }
Beispiel #18
0
        public static async Task ManagementApiMainAsync(string[] args)
        {
            try
            {
                string token = "";

                var api = new ManagementApiClient(token, "jerrie.auth0.com");

                ClientCreateRequest clientCreateRequest = new ClientCreateRequest()
                {
                    Name            = "Test name",
                    ApplicationType = ClientApplicationType.NonInteractive,
                    ResourceServers = new ClientResourceServerAssociation[]
                    {
                        new ClientResourceServerAssociation
                        {
                            Identifier = "urn:test-api",
                            Scopes     = new string[] { "read:appointments", "create:appointments" }
                        }
                    },
                    JwtConfiguration = new JwtConfiguration
                    {
                        SigningAlgorithm  = "RS256",
                        LifetimeInSeconds = 3600
                    }
                };
                var createTask = await api.Clients.CreateAsync(clientCreateRequest);

                //Console.WriteLine($"The tenant has {clients.Count} clients");
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public async Task Disposes_Connection_it_creates_on_dispose()
        {
            var diposeManagement = new ManagementApiClient("token", "test");

            diposeManagement.Dispose();
            await Assert.ThrowsAsync <ObjectDisposedException>(() => diposeManagement.Clients.GetAsync("1"));
        }
        public async Task Test_tenant_settings_sequence()
        {
            string token = await GenerateManagementApiToken();

            var apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"));

            // Get the current settings
            var settings = apiClient.TenantSettings.GetAsync();

            settings.Should().NotBeNull();

            // Update the tenant settings
            var settingsUpdateRequest = new TenantSettingsUpdateRequest
            {
                ErrorPage = new TenantErrorPage
                {
                    Html        = null,
                    ShowLogLink = false,
                    Url         = $"www.{Guid.NewGuid():N}.aaa/error"
                },
                FriendlyName = Guid.NewGuid().ToString("N"),
                PictureUrl   = $"www.{Guid.NewGuid():N}.aaa/picture.png",
                SupportEmail = $"support@{Guid.NewGuid():N}.aaa",
                SupportUrl   = $"www.{Guid.NewGuid():N}.aaa/support"
            };
            var settingsUpdateResponse = await apiClient.TenantSettings.UpdateAsync(settingsUpdateRequest);

            settingsUpdateResponse.Should().BeEquivalentTo(settingsUpdateRequest);
        }
Beispiel #21
0
        public async Task <(Result Result, ShowcaseUser User)> EditUserAsync(string userId, string userName, string name, string description)
        {
            try
            {
                if (tokenExpiresOn <= DateTime.Now)
                {
                    RenewAccessToken();
                }

                var managementClient = new ManagementApiClient(apiToken.AccessToken, Options.Auth0TenantDomain);

                var userMetadata = new Dictionary <string, object>();
                userMetadata.Add("description", description);

                var editedUser = await managementClient.Users.UpdateAsync(userId, new UserUpdateRequest
                {
                    UserName     = userName,
                    FullName     = name,
                    UserMetadata = userMetadata,
                });

                var toReturnUser = _mapper.Map <ShowcaseUser>(editedUser);

                return(Result.Success(), toReturnUser);
            } catch (Exception ex)
            {
                return(Result.Failure(new List <string>(new string[] { ex.Message })), null);
            }
        }
Beispiel #22
0
        public async Task SetUp()
        {
            var scopes = new
            {
                users = new
                {
                    actions = new string[] { "read", "create", "update", "delete" }
                },
                connections = new
                {
                    actions = new string[] { "create", "delete" }
                },
                users_app_metadata = new
                {
                    actions = new string[] { "update" }
                }

            };
            string token = GenerateToken(scopes);

            apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // We will need a connection to add the users to...
            connection = await apiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name = Guid.NewGuid().ToString("N"),
                Strategy = "auth0",
                EnabledClients = new[] { "rLNKKMORlaDzrMTqGtSL9ZSXiBBksCQW" }
            });
        }
        public async Task InitializeAsync()
        {
            string token = await GenerateManagementApiToken();

            _managementApiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"));

            var tenantSettings = await _managementApiClient.TenantSettings.GetAsync();

            if (string.IsNullOrEmpty(tenantSettings.DefaultDirectory))
            {
                throw new Exception("Tests require a tenant with a Default Directory selected.\r\n" +
                                    "Enable OAuth 2.0 API Authorization under Account Settings | General and " +
                                    "select a Default Directory under Account Settings | General");
            }

            // We will need a connection to add the users to...
            _connection = await _managementApiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name           = Guid.NewGuid().ToString("N"),
                Strategy       = "auth0",
                EnabledClients = new [] { GetVariable("AUTH0_CLIENT_ID"), GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID") }
            });

            // And add a dummy user to test against
            _user = await _managementApiClient.Users.CreateAsync(new UserCreateRequest
            {
                Connection    = _connection.Name,
                Email         = $"{Guid.NewGuid():N}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password      = Password
            });
        }
Beispiel #24
0
        public async Task <UserModel> GetUserModel(string token, Auth0ConfigModel objAuth0Config, User user)
        {
            if (user != null)
            {
                var               managementApiClient = new ManagementApiClient(token, objAuth0Config.Domain);
                PaginationInfo    pagination          = new PaginationInfo();
                IPagedList <Role> userRoles           = await managementApiClient.Users.GetRolesAsync(user.UserId, pagination);

                UserMetadata meta = !string.IsNullOrEmpty(Convert.ToString(user.UserMetadata)) ? JsonConvert.DeserializeObject <UserMetadata>(user.UserMetadata.ToString()) : null;

                var userRole = userRoles.Count > 0 ? userRoles[0].Name : "n/a";;

                UserModel objUser = new UserModel
                {
                    Email       = user.Email,
                    FirstName   = user.FirstName,
                    LastName    = user.LastName,
                    PhoneNumber = user.PhoneNumber,
                    PictureUrl  = meta?.Picture,
                    ReportsTo   = meta?.ReportsTo,
                    Role        = userRole
                };

                return(objUser);
            }

            return(null);
        }
        public async Task Test_tenant_settings_sequence()
        {
            var scopes = new
            {
                tenant_settings = new
                {
                    actions = new string[] { "read", "update" }
                }
            };
            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get the current settings
            var settings = apiClient.TenantSettings.Get();
            settings.Should().NotBeNull();

            // Update the tenant settings
            var settingsUpdateRequest = new TenantSettingsUpdateRequest
            {
                ErrorPage = new TenantErrorPage
                {
                    Html = null,
                    ShowLogLink = false,
                    Url = $"www.{Guid.NewGuid().ToString("N")}.aaa/error"
                },
                FriendlyName = Guid.NewGuid().ToString("N"),
                PictureUrl = $"www.{Guid.NewGuid().ToString("N")}.aaa/picture.png",
                SupportEmail = $"support@{Guid.NewGuid().ToString("N")}.aaa",
                SupportUrl = $"www.{Guid.NewGuid().ToString("N")}.aaa/support"
            };
            var settingsUpdateResponse = await apiClient.TenantSettings.Update(settingsUpdateRequest);
            settingsUpdateResponse.ShouldBeEquivalentTo(settingsUpdateRequest);
        }
Beispiel #26
0
        public async Task <IPagedList <Rule> > GetRules()
        {
            //var CLIENTMANAGEMENTSECRET = Environment.GetEnvironmentVariable("CLIENTMANAGEMENTSECRET");
            var CLIENTMANAGEMENTSECRET = Configuration["Auth0:ClientManagementSecret"];

            using (var client = new HttpClient())
            {
                client.BaseAddress = new System.Uri("https://dev-tslblzvb.eu.auth0.com/");
                var response = await client.PostAsync("oauth/token", new FormUrlEncodedContent(
                                                          new Dictionary <string, string>
                {
                    { "grant_type", "client_credentials" },
                    { "client_id", "HArPMSSDB2kMPClUwIgPXs6X4QKJ46HE" },
                    { "client_secret", CLIENTMANAGEMENTSECRET },
                    { "audience", "https://dev-tslblzvb.eu.auth0.com/api/v2/" }
                }
                                                          ));

                var content = await response.Content.ReadAsStringAsync();

                var jsonResult = JObject.Parse(content);

                //get access token for the management api
                var mgmtToken = jsonResult["access_token"].Value <string>();

                using (var mgmtClient = new ManagementApiClient(mgmtToken, new System.Uri("https://dev-tslblzvb.eu.auth0.com/api/v2")))
                {
                    return(await mgmtClient.Rules.GetAllAsync(new GetRulesRequest(), new PaginationInfo()));
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Registers a new user in Auth0 and assigns it the role 'Student'.
        /// </summary>
        /// <exception cref="ArgumentNullException"/>
        /// <exception cref="ArgumentException">Email or password is missing</exception>
        /// <exception cref="ApiException">Auth0 reported an error during registration</exception>
        public static async Task <string> CreateUserAsync(UserRegistrationArgs args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            if (string.IsNullOrEmpty(args.Email))
            {
                throw new ArgumentException("Email is required", nameof(args));
            }

            if (string.IsNullOrEmpty(args.Password))
            {
                throw new ArgumentException("Password is required", nameof(args));
            }

            var accessToken = await GetAccessTokenAsync();

            var management = new ManagementApiClient(accessToken, _authConfig.Domain);
            var user       = await management.Users.CreateAsync(new UserCreateRequest
            {
                Email       = args.Email,
                FirstName   = args.FirstName,
                LastName    = args.LastName,
                FullName    = string.Join(' ', args.FirstName.Trim() ?? "", args.LastName.Trim() ?? ""),
                Password    = args.Password,
                AppMetadata = new { roles = new[] { UserRoles.Student.ToString() } },
                Connection  = "Username-Password-Authentication" // TODO: Make configurable
            });

            return(user.UserId);
        }
        public async Task Test_device_credentials_crud_sequence()
        {
            var apiClient = new ManagementApiClient(GetVariable("AUTH0_TOKEN_DEVICE_CREDENTIALS"), new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            //Get all the device credentials
            var credentialsBefore = await apiClient.DeviceCredentials.GetAllAsync();

            //Create a new device credential
            var newCredentialRequest = new DeviceCredentialCreateRequest
            {
                DeviceName = Guid.NewGuid().ToString("N"),
                DeviceId = Guid.NewGuid().ToString("N"),
                ClientId = client.ClientId,
                UserId = user.UserId,
                Type = "public_key",
                Value = "new-key-value"
            };
            var newCredentialResponse = await apiClient.DeviceCredentials.CreateAsync(newCredentialRequest);
            newCredentialResponse.Should().NotBeNull();
            newCredentialResponse.DeviceId.Should().Be(newCredentialRequest.DeviceId);
            newCredentialResponse.DeviceName.Should().Be(newCredentialRequest.DeviceName);

            // Check that we now have one more device credential
            var credentialsAfterCreate = await apiClient.DeviceCredentials.GetAllAsync();
            credentialsAfterCreate.Count.Should().Be(credentialsBefore.Count + 1);

            // Delete the device credential
            await apiClient.DeviceCredentials.DeleteAsync(newCredentialResponse.Id);

            // Check that we now have one less device credential
            var credentialsAfterDelete = await apiClient.DeviceCredentials.GetAllAsync();
            credentialsAfterDelete.Count.Should().Be(credentialsAfterCreate.Count - 1);
        }
        public IActionResult Create([FromBody] SchoolEditionData model)
        {
            if (ModelState.IsValid)
            {
                var schoolCreationResult = ds.CreateSchool(model);

                UserRecord schoolAdmin = model.SchoolAdmins.First();

                using (var managementClient = new ManagementApiClient())
                {
                    var userAuth0 = managementClient.CreateUser(schoolAdmin);
                    if (userAuth0 != null)
                    {
                        managementClient.RequestVerifyEmail(userAuth0?.UserId);
                    }
                }

                if (schoolCreationResult == ObjectManipulationResult.Success)
                {
                    return(Ok("School successfully created"));
                }
                else if (schoolCreationResult == ObjectManipulationResult.Exists)
                {
                    return(BadRequest("School was not created because school admin account already exists"));
                }
                return(BadRequest("Error occured while creating school"));
            }
            return(BadRequest("Model is not valid"));
        }
Beispiel #30
0
        public async Task InitializeAsync()
        {
            string token = await GenerateManagementApiToken();

            _apiClient = new TestManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"));
            _authenticationApiClient = new TestAuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // We will need a connection to add the users 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") }
            });

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

            _user = await _apiClient.Users.CreateAsync(newUserRequest);

            // Now try and sign in with a wrong password until we get "too many attempts"
            bool userBlocked = false;
            int  attempts    = 0;

            do
            {
                try
                {
                    attempts++;

                    await _authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
                    {
                        ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                        ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                        Realm        = _connection.Name,
                        Scope        = "openid",
                        Username     = _user.Email,
                        Password     = "******"
                    });
                }
                catch (RateLimitApiException)
                {
                    await Task.Delay(1000);
                }
                catch (ErrorApiException ex)
                {
                    if (ex.ApiError.Error == "too_many_attempts")
                    {
                        userBlocked = true;
                    }
                }
            } while (!userBlocked && attempts < 20); // Add failsafe to stop if we go over 20 attempts. User should be blocked by then, but just to make sure...
        }
Beispiel #31
0
        public async Task Test_rules_crud_sequence()
        {
            var scopes = new
            {
                rules = new
                {
                    actions = new string[] { "read", "create", "delete", "update" }
                }
            };

            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get all rules
            var rulesBefore = await apiClient.Rules.GetAllAsync();

            // Add a new rule
            var newRuleRequest = new RuleCreateRequest
            {
                Name   = $"integration-test-rule-{Guid.NewGuid().ToString("N")}",
                Script = @"function (user, context, callback) {
                              // TODO: implement your rule
                              callback(null, user, context);
                            }"
            };
            var newRuleResponse = await apiClient.Rules.CreateAsync(newRuleRequest);

            newRuleResponse.Should().NotBeNull();
            newRuleResponse.Name.Should().Be(newRuleRequest.Name);

            // Get all the rules again, and check that we now have one more
            var rulesAfter = await apiClient.Rules.GetAllAsync();

            rulesAfter.Count.Should().Be(rulesBefore.Count + 1);

            // Update the Rule
            var updateRuleRequest = new RuleUpdateRequest
            {
                Name = $"integration-test-rule-{Guid.NewGuid().ToString("N")}"
            };
            var updateRuleResponse = await apiClient.Rules.UpdateAsync(newRuleResponse.Id, updateRuleRequest);

            updateRuleResponse.Should().NotBeNull();
            updateRuleResponse.Name.Should().Be(updateRuleRequest.Name);

            // Get a single rule
            var rule = await apiClient.Rules.GetAsync(newRuleResponse.Id);

            rule.Should().NotBeNull();
            rule.Name.Should().Be(updateRuleRequest.Name);

            // Delete the rule, and ensure we get exception when trying to fetch it again
            await apiClient.Rules.DeleteAsync(rule.Id);

            Func <Task> getFunc = async() => await apiClient.Rules.GetAsync(rule.Id);

            getFunc.ShouldThrow <ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_rule");
        }
Beispiel #32
0
        public async Task Test_connection_crud_sequence()
        {
            string token = await GenerateManagementApiToken();

            var apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL"));

            // Get all connections before
            var connectionsBefore = await apiClient.Connections.GetAllAsync("github");

            // Create a new connection
            var newConnectionRequest = new ConnectionCreateRequest
            {
                Name     = Guid.NewGuid().ToString("N"),
                Strategy = "github"
            };
            var newConnectionResponse = await apiClient.Connections.CreateAsync(newConnectionRequest);

            newConnectionResponse.Should().NotBeNull();
            newConnectionResponse.Name.Should().Be(newConnectionRequest.Name);
            newConnectionResponse.Strategy.Should().Be(newConnectionRequest.Strategy);

            // Get all connections again
            var connectionsAfter = await apiClient.Connections.GetAllAsync("github");

            connectionsAfter.Count.Should().Be(connectionsBefore.Count + 1);

            // Update a connection
            var updateConnectionRequest = new ConnectionUpdateRequest
            {
                Options = new
                {
                    a = "123"
                },
                Metadata = new
                {
                    b = "456"
                }
            };
            var updateConnectionResponse = await apiClient.Connections.UpdateAsync(newConnectionResponse.Id, updateConnectionRequest);

            string a = updateConnectionResponse.Options.a;

            a.Should().Be("123");
            string b = updateConnectionResponse.Metadata.b;

            b.Should().Be("456");

            // Get a single connection
            var connection = await apiClient.Connections.GetAsync(newConnectionResponse.Id);

            connection.Should().NotBeNull();

            // Delete the connection and ensure we get exception when trying to get connection again
            await apiClient.Connections.DeleteAsync(newConnectionResponse.Id);

            Func <Task> getFunc = async() => await apiClient.Connections.GetAsync(newConnectionResponse.Id);

            getFunc.ShouldThrow <ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_connection");
        }
        public async Task Cleanup()
        {
            var apiClient = new ManagementApiClient(GetVariable("AUTH0_TOKEN_DEVICE_CREDENTIALS"), new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            await apiClient.Clients.DeleteAsync(client.ClientId);
            await apiClient.Connections.DeleteAsync(connection.Id);
            await apiClient.Users.DeleteAsync(user.UserId);
        }
Beispiel #34
0
        public async Task Test_rules_crud_sequence()
        {
            var scopes = new
            {
                rules = new
                {
                    actions = new string[] { "read", "create", "delete", "update" }
                }
            };

            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get all rules
            var rulesBefore = await apiClient.Rules.GetAll();

            // Add a new rule
            var newRuleRequest = new RuleCreateRequest
            {
                Name = $"integration-test-rule-{Guid.NewGuid().ToString("N")}",
                Script = @"function (user, context, callback) {
                              // TODO: implement your rule
                              callback(null, user, context);
                            }"
            };
            var newRuleResponse = await apiClient.Rules.Create(newRuleRequest);
            newRuleResponse.Should().NotBeNull();
            newRuleResponse.Name.Should().Be(newRuleRequest.Name);

            // Get all the rules again, and check that we now have one more
            var rulesAfter = await apiClient.Rules.GetAll();
            rulesAfter.Count.Should().Be(rulesBefore.Count + 1);

            // Update the Rule
            var updateRuleRequest = new RuleUpdateRequest
            {
                Name = $"integration-test-rule-{Guid.NewGuid().ToString("N")}"
            };
            var updateRuleResponse = await apiClient.Rules.Update(newRuleResponse.Id, updateRuleRequest);
            updateRuleResponse.Should().NotBeNull();
            updateRuleResponse.Name.Should().Be(updateRuleRequest.Name);

            // Get a single rule
            var rule = await apiClient.Rules.Get(newRuleResponse.Id);
            rule.Should().NotBeNull();
            rule.Name.Should().Be(updateRuleRequest.Name);

            // Delete the rule, and ensure we get exception when trying to fetch it again
            await apiClient.Rules.Delete(rule.Id);
            Func<Task> getFunc = async () => await apiClient.Rules.Get(rule.Id);
            getFunc.ShouldThrow<ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_rule");
        }
Beispiel #35
0
        public async Task Test_client_crud_sequence()
        {
            var scopes = new
            {
                clients = new
                {
                    actions = new string[] { "read", "create", "delete", "update" }
                },
                client_keys = new
                {
                    actions = new string[] { "read", "update" }
                }
            };
            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get all clients
            var clientsBefore = await apiClient.Clients.GetAllAsync();

            // Add a new client
            var newClientRequest = new ClientCreateRequest
            {
                Name = $"Integration testing {Guid.NewGuid().ToString("N")}"
            };
            var newClientResponse = await apiClient.Clients.CreateAsync(newClientRequest);
            newClientResponse.Should().NotBeNull();
            newClientResponse.Name.Should().Be(newClientRequest.Name);

            // Get all clients again, and ensure we have one client more
            var clientsAfter = await apiClient.Clients.GetAllAsync();
            clientsAfter.Count.Should().Be(clientsBefore.Count + 1);

            // Update the client
            var updateClientRequest = new ClientUpdateRequest
            {
                Name = $"Integration testing {Guid.NewGuid().ToString("N")}"
            };
            var updateClientResponse = await apiClient.Clients.UpdateAsync(newClientResponse.ClientId, updateClientRequest);
            updateClientResponse.Should().NotBeNull();
            updateClientResponse.Name.Should().Be(updateClientRequest.Name);

            // Get a single client
            var client = await apiClient.Clients.GetAsync(newClientResponse.ClientId);
            client.Should().NotBeNull();
            client.Name.Should().Be(updateClientResponse.Name);

            // Delete the client, and ensure we get exception when trying to fetch client again
            await apiClient.Clients.DeleteAsync(client.ClientId);
            Func<Task> getFunc = async () => await apiClient.Clients.GetAsync(client.ClientId);
            getFunc.ShouldThrow<ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_client");
        }
Beispiel #36
0
        public async Task Test_connection_crud_sequence()
        {
            var scopes = new
            {
                connections = new
                {
                    actions = new string[] { "read", "create", "delete", "update" }
                }
            };
            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get all connections before
            var connectionsBefore = await apiClient.Connections.GetAllAsync("github");

            // Create a new connection
            var newConnectionRequest = new ConnectionCreateRequest
            {
                Name = Guid.NewGuid().ToString("N"),
                Strategy = "github"
            };
            var newConnectionResponse = await apiClient.Connections.CreateAsync(newConnectionRequest);
            newConnectionResponse.Should().NotBeNull();
            newConnectionResponse.Name.Should().Be(newConnectionRequest.Name);
            newConnectionResponse.Strategy.Should().Be(newConnectionRequest.Strategy);

            // Get all connections again
            var connectionsAfter = await apiClient.Connections.GetAllAsync("github");
            connectionsAfter.Count.Should().Be(connectionsBefore.Count + 1);

            // Update a connection
            var updateConnectionRequest = new ConnectionUpdateRequest
            {
                Options = new
                {
                    a = "123"
                }
            };
            var updateConnectionResponse = await apiClient.Connections.UpdateAsync(newConnectionResponse.Id, updateConnectionRequest);
            //updateConnectionResponse.Name.Should().Be(updateConnectionRequest.Name);

            // Get a single connection
            var connection = await apiClient.Connections.GetAsync(newConnectionResponse.Id);
            connection.Should().NotBeNull();
            //connection.Name.Should().Be(updateConnectionResponse.Name);

            // Delete the connection and ensure we get exception when trying to get connection again
            await apiClient.Connections.DeleteAsync(newConnectionResponse.Id);
            Func<Task> getFunc = async () => await apiClient.Connections.GetAsync(newConnectionResponse.Id);
            getFunc.ShouldThrow<ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_connection");
        }
        public async Task Test_blacklist_sequence()
        {
            string apiKey = GetVariable("AUTH0_API_KEY");

            var apiClient = new ManagementApiClient(GetVariable("AUTH0_TOKEN_BLACKLISTED_TOKENS"), new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get all the blacklisted tokens
            var tokensBefore = await apiClient.BlacklistedTokens.GetAll(apiKey);

            // Generate a token which allows us to list all clients
            var scopes = new
            {
                clients = new
                {
                    actions = new string[] { "read" }
                }
            };
            string jti = Guid.NewGuid().ToString("N");
            string token = GenerateToken(scopes, jti);

            // Confirm that the token is working
            var confirmationApiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));
            var clients = await confirmationApiClient.Clients.GetAll();
            clients.Should().NotBeNull();

            // Now blacklist that new token
            var blacklistRequest = new BlacklistedTokenCreateRequest
            {
                Aud = apiKey,
                Jti = jti
            };
            await apiClient.BlacklistedTokens.Create(blacklistRequest);

            // Get all the blacklisted tokens and check that we have one more
            var tokensAfter = await apiClient.BlacklistedTokens.GetAll(apiKey);
            tokensAfter.Count.Should().Be(tokensBefore.Count + 1);

            // Try and get all the clients again with that token
            Func<Task> getFunc = async () => await confirmationApiClient.Clients.GetAll();
            getFunc.ShouldThrow<ApiException>().And.ApiError.StatusCode.Should().Be(401);
        }
Beispiel #38
0
        public async Task Test_stats_sequence()
        {
            var scopes = new
            {
                stats = new
                {
                    actions = new string[] { "read" }
                }
            };
            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get stats for the past 10 days
            var dailyStats = await apiClient.Stats.GetDailyStatsAsync(DateTime.Now.AddDays(-10), DateTime.Now);
            dailyStats.Should().NotBeNull();

            // Get the active users
            var activeUsers = await apiClient.Stats.GetActiveUsersAsync();
            activeUsers.Should().BeGreaterOrEqualTo(0);
        }
        public async Task Initialize()
        {
            var apiClient = new ManagementApiClient(GetVariable("AUTH0_TOKEN_DEVICE_CREDENTIALS"), new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Set up the correct Client, Connection and User
            client = await apiClient.Clients.CreateAsync(new ClientCreateRequest
            {
                Name = Guid.NewGuid().ToString("N")
            });
            connection = await apiClient.Connections.CreateAsync(new ConnectionCreateRequest
            {
                Name = Guid.NewGuid().ToString("N"),
                Strategy = "auth0"
            });
            user = await apiClient.Users.CreateAsync(new UserCreateRequest
            {
                Connection = connection.Name,
                Email = $"{Guid.NewGuid().ToString("N")}@nonexistingdomain.aaa",
                EmailVerified = true,
                Password = "******"
            });
        }
Beispiel #40
0
        public async Task Test_email_provider_crud_sequence()
        {
            var scopes = new
            {
                email_provider = new
                {
                    actions = new string[] { "read", "create", "delete", "update" }
                }
            };
            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Delete the email provider to ensure we start on a clean slate
            await apiClient.EmailProvider.DeleteAsync();

            // Getting the email provider now should throw, since none is configured
            Func<Task> getFunc = async () => await apiClient.EmailProvider.GetAsync("name,enabled,credentials,settings");
            getFunc.ShouldThrow<ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_email_provider");

            // Configure the email provider
            var configureRequest = new EmailProviderConfigureRequest
            {
                Name = "mandrill",
                IsEnabled = true,
                Credentials = new EmailProviderCredentials
                {
                    ApiKey = "ABC"
                }
            };
            var configureResponse = await apiClient.EmailProvider.ConfigureAsync(configureRequest);
            configureResponse.Name.Should().Be(configureRequest.Name);
            configureResponse.IsEnabled.Should().Be(configureRequest.IsEnabled);
            configureResponse.Credentials.ApiKey.Should().Be(configureRequest.Credentials.ApiKey);

            // Check that we can get the email provider details 
            var provider = await apiClient.EmailProvider.GetAsync("name,enabled,credentials,settings");
            provider.Name.Should().Be(configureRequest.Name);
            provider.IsEnabled.Should().Be(configureRequest.IsEnabled);
            provider.Credentials.ApiKey.Should().Be(configureRequest.Credentials.ApiKey);

            // Update the email provider
            var updateRequest = new EmailProviderUpdateRequest
            {
                Name = "mandrill",
                IsEnabled = true,
                Credentials = new EmailProviderCredentials
                {
                    ApiKey = "XYZ"
                }
            };
            var updateResponse = await apiClient.EmailProvider.UpdateAsync(updateRequest);
            updateResponse.Name.Should().Be(updateRequest.Name);
            updateResponse.IsEnabled.Should().Be(updateRequest.IsEnabled);
            updateResponse.Credentials.ApiKey.Should().Be(updateRequest.Credentials.ApiKey);

            // Delete the email provider again
            await apiClient.EmailProvider.DeleteAsync();

            // Check than once again the email provider should throw, since none is configured
            getFunc = async () => await apiClient.EmailProvider.GetAsync("name,enabled,credentials,settings");
            getFunc.ShouldThrow<ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_email_provider");

        }