public async Task GetAllTenantAsyncTest() { // Arrange UserTenantListModel userTenants = new UserTenantListModel("GetAllTenants", new List <UserTenantModel>()); this.mockTenantContainer.Setup(x => x.GetAllTenantsAsync(It.IsAny <string>())) .ReturnsAsync(userTenants); // Act var result = await this.controller.GetTenantsAsync(); // Assert Assert.Equal(result.BatchMethod, userTenants.BatchMethod); Assert.Equal(result.Models, userTenants.Models); }
public async Task <IActionResult> PostTokenAsync( [FromBody] ClientCredentialInput input) { string resourceUri = "https://graph.microsoft.com/"; ClientCredential clientCredential = new ClientCredential(input.ClientId, input.ClientSecret); try { AuthenticationResult token = await this.authenticationContext.AcquireTokenAsync(resourceUri, clientCredential); } catch (Exception e) { return(this.StatusCode(401, e.Message)); } UserTenantInput tenantInput = new UserTenantInput { UserId = input.ClientId, Tenant = input.Scope, }; UserTenantListModel tenantsModel = await this.userTenantContainer.GetAllAsync(tenantInput); if (tenantsModel.Models.Count == 0) { throw new Exception("Not granted access to that tenant"); } DateTime?expirationTime = null; if (this.config.Global.ClientAuth.TokenExpirationDuration != null) { expirationTime = DateTime.Now.Add(TimeSpan.ParseExact(this.config.Global.ClientAuth.TokenExpirationDuration, "c", null)); } // if successful, then mint token var jwtHandler = new JwtSecurityTokenHandler(); var claims = new List <Claim>(); claims.Add(new Claim("client_id", input.ClientId)); claims.Add(new Claim("sub", input.ClientId)); claims.Add(new Claim("name", input.ClientId)); claims.Add(new Claim("type", "Client Credentials")); string tokenString = jwtHandler.WriteToken(await this.jwtHelper.GetIdentityToken(claims, input.Scope, "IoTPlatform", expirationTime)); return(this.StatusCode(200, tokenString)); }
public virtual async Task <UserTenantListModel> DeleteAllAsync(UserTenantInput input) { UserTenantListModel tenantRows = await this.GetAllUsersAsync(input); // delete all rows as one asynchronous job var deleteTasks = tenantRows.Models.Select(row => { UserTenantInput deleteInput = new UserTenantInput { UserId = row.PartitionKey, Tenant = input.Tenant, }; return(this.DeleteAsync(deleteInput)); }); var deletionResult = await Task.WhenAll(deleteTasks); return(new UserTenantListModel("Delete", deletionResult.ToList())); }
public async Task <UserTenantListModel> GetAllTenantsAsync(string userId) { try { IdentityGatewayApiListModel identityGatewayUserTenants = await this.identityGatewayClient.GetAllTenantsForUserAsync(userId); UserTenantListModel userTenants = new UserTenantListModel(identityGatewayUserTenants); foreach (var userTenant in userTenants.Models) { userTenant.TenantName = await this.GetTenantNameAsync(userTenant.TenantId); } return(userTenants); } catch (Exception e) { throw new Exception("Unable to retrieve the tenants", e); } }
private async Task AddUserForPendingTenants(SystemAdminModel result, string createdBy) { if (result != null) { TenantListModel activeTenants = await this.userTenantcontainer.GetAllActiveTenantAsync(); if (activeTenants != null && activeTenants.Models != null && activeTenants.Models.Count > 0) { List <string> activeTenantIds = activeTenants.Models.Select(x => x.TenantId).ToList(); if (activeTenantIds != null && activeTenantIds.Count > 0) { UserTenantInput userInput = new UserTenantInput() { UserId = result.PartitionKey, Name = result.Name, Roles = JsonConvert.SerializeObject(new List <string>() { AdminRole }), Type = MemberType, }; UserTenantListModel existingTenants = await this.userTenantcontainer.GetAllAsync(userInput); for (int i = 0; i < activeTenantIds.Count; i++) { userInput.Tenant = activeTenantIds[i]; if (existingTenants != null && existingTenants.Models != null && existingTenants.Models.FirstOrDefault(x => x.UserId == userInput.UserId && x.TenantId == userInput.Tenant) == null) { // Adding Audit Data userInput.CreatedBy = createdBy; userInput.CreatedTime = DateTime.UtcNow; var createdUser = await this.userTenantcontainer.CreateAsync(userInput); } } } } } }
public async Task <UserTenantListModel> GetAllTenantsAsync(string userId) { try { IdentityGatewayApiListModel identityGatewayUserTenants = await this.identityGatewayClient.GetAllTenantsForUserAsync(userId); UserTenantListModel userTenants = new UserTenantListModel(identityGatewayUserTenants); foreach (var userTenant in userTenants.Models) { var tenantResponse = await this.GetTenantNameAsync(userTenant.TenantId); userTenant.TenantName = tenantResponse != null && !string.IsNullOrWhiteSpace(tenantResponse.TenantName) ? tenantResponse.TenantName : $"tenant#{tenantResponse.TenantId.Substring(0, 5)}"; userTenant.IotHubName = tenantResponse != null && !string.IsNullOrWhiteSpace(tenantResponse.IotHubName) ? tenantResponse.IotHubName : string.Empty; } return(userTenants); } catch (Exception e) { throw new Exception("Unable to retrieve the tenants", e); } }
public async Task <JwtSecurityToken> GetIdentityToken(List <Claim> claims, string tenant, string audience, DateTime?expiration) { // add iat claim var timeSinceEpoch = DateTime.UtcNow.ToEpochTime(); claims.Add(new Claim("iat", timeSinceEpoch.ToString(), ClaimValueTypes.Integer)); var userId = claims.First(t => t.Type == "sub").Value; // Create a userTenantInput for the purpose of finding the full tenant list associated with this user UserTenantInput tenantInput = new UserTenantInput { UserId = userId, }; UserTenantListModel tenantsModel = await this.userTenantContainer.GetAllAsync(tenantInput); List <UserTenantModel> tenantList = tenantsModel.Models; // User did not specify the tenant to log into so get the default or last used if (string.IsNullOrEmpty(tenant)) { // authState has no tenant, so we should use either the User's last used tenant, or the first tenant available to them // Create a UserSettingsInput for the purpose of finding the LastUsedTenant setting for this user this.logger.LogInformation("User did not specify Tenant so default/last used tenant is set."); UserSettingsInput settingsInput = new UserSettingsInput { UserId = userId, SettingKey = "LastUsedTenant", }; UserSettingsModel lastUsedSetting = await this.userSettingsContainer.GetAsync(settingsInput); // Has last used tenant and it is in the list if (lastUsedSetting != null && tenantList.Count(t => t.TenantId == lastUsedSetting.Value) > 0) { tenant = lastUsedSetting.Value; } if (string.IsNullOrEmpty(tenant) && tenantList.Count > 0) { tenant = tenantList.First() .TenantId; // Set the tenant to the first tenant in the list of tenants for this user } } // If User not associated with Tenant then dont add claims return token without if (tenant != null) { UserTenantInput input = new UserTenantInput { UserId = userId, Tenant = tenant, }; UserTenantModel tenantModel = await this.userTenantContainer.GetAsync(input); // Add Tenant claims.Add(new Claim("tenant", tenantModel.TenantId)); // Add Roles tenantModel.RoleList.ForEach(role => claims.Add(new Claim("role", role))); // Settings Update LastUsedTenant UserSettingsInput settingsInput = new UserSettingsInput { UserId = claims.Where(c => c.Type == "sub").First().Value, SettingKey = "LastUsedTenant", Value = tenant, }; // Update if name is not the same await this.userSettingsContainer.UpdateAsync(settingsInput); if (tenantModel.Name != claims.Where(c => c.Type == "name").First().Value) { input.Name = claims.Where(c => c.Type == "name").First().Value; await this.userTenantContainer.UpdateAsync(input); } } DateTime expirationDateTime = expiration ?? DateTime.Now.AddDays(30); // add all tenants they have access to claims.AddRange(tenantList.Select(t => new Claim("available_tenants", t.TenantId))); // Token to String so you can use it in your client var token = this.MintToken(claims, audience, expirationDateTime); return(token); }