public async Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); if (role == null) { throw new ArgumentNullException(nameof(role)); } if (claim == null) { throw new ArgumentNullException(nameof(claim)); } var currentClaim = role.Claims .FirstOrDefault(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); if (currentClaim == null) { var identityRoleClaim = new IdentityRoleClaim <string>() { ClaimType = claim.Type, ClaimValue = claim.Value }; role.Claims.Add(identityRoleClaim); await _collection.UpdateOneAsync(x => x.Id == role.Id, Builders <TRole> .Update.Set(x => x.Claims, role.Claims), cancellationToken : cancellationToken); } }
public async Task <ActionResult> Create(ApplicationRole Rol) { var validation = await db.Roles.Where(n => n.Name == Rol.Name).CountAsync(); if (validation > 0) { ModelState.AddModelError("", "El nombre del rol ya ha sido usado."); return(View(Rol)); } Rol.NormalizedName = Rol.Name.ToUpper(); if (ModelState.IsValid) { db.Roles.Add(Rol); await db.SaveChangesAsync(); var policies = await db.Policy.ToListAsync(); var claims = new List <IdentityRoleClaim <string> >(); foreach (var p in policies) { var claim = new IdentityRoleClaim <string>(); claim.RoleId = Rol.Id; claim.ClaimValue = "0"; claim.ClaimType = p.claim; claims.Add(claim); } db.RoleClaims.AddRange(claims); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(Rol)); }
public async Task <ClaimResult> AssignClaimsToRoleAsync(Role role, IEnumerable <TEntity> claim) { ThrowIfDisposed(); try { foreach (var item in claim) { var c = new IdentityRoleClaim <int>() { ClaimType = item.Type, ClaimValue = item.Value }; unitOfWork.Database.Set <IdentityRoleClaim <int> >().Add(c); await unitOfWork.Commit(); } return(new ClaimResult() { Succeed = true }); } catch (Exception ex) { return(new ClaimResult() { Succeed = false, Exceptions = ex }); } }
internal async override Task <IdentityRoleClaim <string> > IncluirAsync(IdentityRoleClaim <string> entidade) { try { this.usuarioContexto.Database.BeginTransaction(this.isolationLevel); this.usuarioContexto.RoleClaims.Add(entidade); Task <int> registrosAfetados = this.usuarioContexto.SaveChangesAsync(); if (registrosAfetados.Result > 0) { this.usuarioContexto.Database.CurrentTransaction.Commit(); } else { this.usuarioContexto.Database.CurrentTransaction.Rollback(); } await registrosAfetados; return(entidade); } catch (Exception ex) { if (this.usuarioContexto.Database.CurrentTransaction != null) { this.usuarioContexto.Database.CurrentTransaction.Rollback(); } throw ex; } }
public async Task <IActionResult> Update([FromBody] RoleModel model) { bool createMode = false; // Save role ApplicationRole role = _roleManager.Roles.SingleOrDefault(r => r.Id == model.Id); if (role == null) { createMode = true; role = new ApplicationRole(); } role.Name = model.Name; // Save permissions IdentityRoleClaim <string> currentPermission = null; IList <PermissionInfo> permissions = _securityManager.GetPermissionsList(); IList <IdentityRoleClaim <string> > currentPermissions = role.Claims.ToList(); if (createMode) { await _roleManager.CreateAsync(role); } else { await _roleManager.UpdateAsync(role); } foreach (PermissionInfo permission in permissions) { currentPermission = currentPermissions.SingleOrDefault(c => c.ClaimType == ModuleConfiguration.ModulePermissionType && c.ClaimValue == permission.PermissionId.ToString()); if (currentPermission != null) { if (!model.Permissions.Any(sp => sp == permission.PermissionId)) { await _roleManager.RemoveClaimAsync(role, currentPermission.ToClaim()); } } else { if (model.Permissions.Any(sp => sp == permission.PermissionId)) { currentPermission = new IdentityRoleClaim <string>(); currentPermission.ClaimType = ModuleConfiguration.ModulePermissionType; currentPermission.ClaimValue = permission.PermissionId.ToString(); currentPermission.RoleId = role.Id; await _roleManager.AddClaimAsync(role, currentPermission.ToClaim()); } } } return(Ok(new { RoleId = role.Id })); }
public Task AddClaim(IdentityRoleClaim <Guid> claim) { if (Exists && claim != null) { _data.State.Claims.Add(claim); return(_data.WriteStateAsync()); } return(Task.CompletedTask); }
public static Entity.RoleClaim ToEntity(this IdentityRoleClaim <string> claim) { return(new Entity.RoleClaim { Id = $"{claim.RoleId}@{claim.Id}", RoleId = claim.RoleId, ClaimType = claim.ClaimType, ClaimValue = claim.ClaimValue }); }
public async Task Seed() { if (!(await _roleMgr.RoleExistsAsync("Client"))) { var role = new IdentityRole("Client"); var adminClaim = new IdentityRoleClaim <string>() { ClaimType = "IsAdmin", ClaimValue = "False" }; await _roleMgr.CreateAsync(role); await _roleMgr.AddClaimAsync(role, adminClaim.ToClaim()); } var user = await _userMgr.FindByNameAsync("storesysadmin"); // Add User if (user == null) { if (!(await _roleMgr.RoleExistsAsync("Admin"))) { var role = new IdentityRole("Admin"); var adminClaim = new IdentityRoleClaim <string>() { ClaimType = "IsAdmin", ClaimValue = "True" }; await _roleMgr.CreateAsync(role); await _roleMgr.AddClaimAsync(role, adminClaim.ToClaim()); } user = new UserEntity() { UserName = "******", FirstName = "Store", LastName = "SysAdmin", Email = _config["sysadmin_email"] }; var userResult = await _userMgr.CreateAsync(user, _config["sysadmin_password"]); var roleResult = await _userMgr.AddToRoleAsync(user, "Admin"); var claimResult = await _userMgr.AddClaimAsync(user, new Claim("SuperUser", "True")); if (!userResult.Succeeded || !roleResult.Succeeded || !claimResult.Succeeded) { throw new InvalidOperationException("Failed to build user and roles"); } } }
private async Task CraeteRegularUserRole() { var regularUser = await _roleManager.RoleExistsAsync(Roles.RegularUser.ToString()); if (!regularUser) { var role = new IdentityRole(Roles.RegularUser.ToString()); var claim = new IdentityRoleClaim <string> { ClaimType = "IsRegularUser", ClaimValue = "True" }; role.Claims.Add(claim); await _roleManager.CreateAsync(role); } }
internal static RequisicaoTableViewModel converterIdentityRoleClaimParaClaim(IdentityRoleClaim <string> identityRoleClaim) { RequisicaoTableViewModel funcaoRequisicaoTableViewModel = null; if (identityRoleClaim != null) { Claim claim = identityRoleClaim.ToClaim(); funcaoRequisicaoTableViewModel = new RequisicaoTableViewModel(); funcaoRequisicaoTableViewModel.Id = identityRoleClaim.Id; funcaoRequisicaoTableViewModel.Type = claim.Type; funcaoRequisicaoTableViewModel.ValueType = claim.ValueType; funcaoRequisicaoTableViewModel.Value = claim.Value; } return(funcaoRequisicaoTableViewModel); }
protected virtual void CreateRoleScopes(DbContextIdentityBase <TUser> context, IEnumerable <SeedRole> roles) { foreach (var role in roles) { foreach (var scope in role.Scopes) { if (context.RoleClaims.Where(rc => rc.RoleId == role.Name && rc.ClaimType == "scope" && rc.ClaimValue == scope).FirstOrDefault() == null) { var claim = new IdentityRoleClaim <string>() { ClaimType = "scope", ClaimValue = scope, RoleId = role.Name }; context.RoleClaims.Add(claim); } } var remove = context.RoleClaims.Where(rc => rc.RoleId == role.Name && rc.ClaimType == "scope" && !role.Scopes.Contains(rc.ClaimValue)).ToList(); context.RoleClaims.RemoveRange(remove); } }
public async Task <IActionResult> OnGetAsync(int?id) { role = await GetRole(); if (role == null) { return(NotFound("Không thấy Role")); } if (id == null) { return(NotFound()); } EditClaim = await _context.RoleClaims.FirstOrDefaultAsync(m => m.Id == id); if (EditClaim == null) { return(NotFound()); } return(Page()); }
private void AddOrUpdateClaim(UserRole role, string claimType) { var claimInDb = this.db .RoleClaims .FirstOrDefault(rc => rc.ClaimType == claimType); if (claimInDb == null) { var claimToAdd = new IdentityRoleClaim <int>() { ClaimType = claimType, RoleId = role.Id, ClaimValue = claimType }; this.db.RoleClaims.Add(claimToAdd); } else { role.Claims.Add(claimInDb); } }
/// <summary> /// Adds the <paramref name="claim"/> given to the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to add the claim to.</param> /// <param name="claim">The claim to add to the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public async Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default) { ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } if (claim == null) { throw new ArgumentNullException(nameof(claim)); } var identityRoleClaim = new IdentityRoleClaim <string>() { ClaimType = claim.Type, ClaimValue = claim.Value }; role.Claims.Add(identityRoleClaim); await _collection.UpdateOneAsync(x => x.Id.Equals(role.Id), Builders <TRole> .Update.Set(x => x.Claims, role.Claims), cancellationToken : cancellationToken).ConfigureAwait(false); }
public async Task AddClaimsAsync(TRole role, IEnumerable <Claim> claims, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); foreach (var claim in claims) { var currentClaim = role.Claims .FirstOrDefault(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); if (currentClaim == null) { var identityRoleClaim = new IdentityRoleClaim <string>() { ClaimType = claim.Type, ClaimValue = claim.Value }; role.Claims.Add(identityRoleClaim); } } await _collection.UpdateOneAsync(x => x.Id == role.Id, Builders <TRole> .Update.Set(x => x.Claims, role.Claims), cancellationToken : cancellationToken); //await Add(user, x => x.Claims, identityClaim); }
public async Task <IActionResult> OnPostAsync(int?id) { role = await GetRole(); if (role == null) { return(NotFound("Không thấy Role")); } if (id == null) { return(NotFound()); } EditClaim = await _context.RoleClaims.FindAsync(id); if (EditClaim != null) { _context.RoleClaims.Remove(EditClaim); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index", new { roleid = roleid })); }
public async Task <ActionResult> Edit(ApplicationRole Rol) { var validation = await db.Roles.Where(n => n.Name == Rol.Name && n.Id != Rol.Id).CountAsync(); if (validation > 0) { ModelState.AddModelError("", "El nombre del rol ya ha sido usado."); } Rol.NormalizedName = Rol.Name.ToUpper(); if (ModelState.IsValid && validation == 0) { db.Entry(Rol).State = EntityState.Modified; await db.SaveChangesAsync(); // INICIO - Actualizar permisos var claims = new List <String>(); var permisosDb = await db.RoleClaims.Where(n => n.RoleId == Rol.Id).ToListAsync(); foreach (var per in permisosDb) { var valor = HttpContext.Request.Form["p_" + per.Id].ToString(); if (valor != null) { claims.Add(per.ClaimType); per.ClaimValue = valor == "" ? "0" : valor; db.Entry(per).State = EntityState.Modified; await db.SaveChangesAsync(); } } //FIN - Actualizar permisos // INICIO - Agregar permisos para policies nuevas var newPolicies = await db.Policy.Where(n => !claims.Contains(n.claim)).ToListAsync(); var newClaims = new List <IdentityRoleClaim <string> >(); foreach (var p in newPolicies) { var valor = HttpContext.Request.Form["n_" + p.id].ToString(); var claim = new IdentityRoleClaim <string>(); claim.RoleId = Rol.Id; claim.ClaimValue = valor != null && valor != "" ? valor : "0"; claim.ClaimType = p.claim; newClaims.Add(claim); } db.RoleClaims.AddRange(newClaims); await db.SaveChangesAsync(); // FIN - Agregar permisos para policies nuevas return(RedirectToAction("Index")); } var policies = await db.Policy.ToDictionaryAsync(n => n.claim, n => n.nombre); var permisos = await db.RoleClaims.Where(n => n.RoleId == Rol.Id) .Select(n => new PermisoDataModel { id = n.Id, valor = n.ClaimValue, texto = n.ClaimType }) .ToListAsync(); foreach (var per in permisos) { if (policies.ContainsKey(per.texto)) { per.texto = policies[per.texto]; } } ViewBag.Permisos = permisos; return(View(Rol)); }
public async Task <IActionResult> Account([FromBody] AccountViewModel model, [FromServices] ApplicationDbContext applicationDbContext, [FromServices] IApplicationManager applicationManager, [FromServices] IModuleManager moduleManager, [FromServices] UserManager <ApplicationUser> userManager, [FromServices] RoleManager <ApplicationRole> roleManager, [FromServices] SignInManager <ApplicationUser> signInManager) { if (ModelState.IsValid) { string connectionString = _configuration.GetConnectionString("DefaultConnection"); if (String.IsNullOrEmpty(connectionString) || DatabaseExists(connectionString, true)) { return(BadRequest()); } try { // Create identity tables applicationDbContext.Database.Migrate(); // Create host user ApplicationUser user = new ApplicationUser { UserName = model.Email, Email = model.Email, EmailConfirmed = true }; IdentityResult result = await userManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return(BadRequest(result.Errors)); } // Install roles ApplicationRole role = new ApplicationRole(); role.Name = "Administrator"; await roleManager.CreateAsync(role); IdentityRoleClaim <String> roleClaim = new IdentityRoleClaim <String>(); roleClaim.ClaimType = "GlobalSettingsEdition"; roleClaim.ClaimValue = "GlobalSettingsEdition"; roleClaim.RoleId = role.Id; await roleManager.AddClaimAsync(role, roleClaim.ToClaim()); // Add user to admin role await userManager.AddToRoleAsync(user, role.Name); // Create kastra tables applicationManager.Install(); // Install default template applicationManager.InstallDefaultTemplate(); // Install default page applicationManager.InstallDefaultPage(); // Install default permissions applicationManager.InstallDefaultPermissions(); // Install modules moduleManager.InstallModules(); } catch (Exception ex) { return(BadRequest(ex.Message)); } } return(Ok()); }
public static async Task SeedDb(ApplicationDbContext context, UserManager <IdentityUser> userManager, RoleManager <IdentityRole> roleManager) { context.Database.EnsureCreated(); if (!context.Roles.Any()) { await roleManager.CreateAsync(new IdentityRole("admin")); await roleManager.CreateAsync(new IdentityRole("user")); } var adminRole = roleManager.Roles.FirstOrDefault(x => x.Name == "admin"); var userRole = roleManager.Roles.FirstOrDefault(x => x.Name == "user"); var claim1 = new IdentityRoleClaim <string> { ClaimType = "CanCreatePost", ClaimValue = "CanCreatePost" }; var claim2 = new IdentityRoleClaim <string> { ClaimType = "CanComment", ClaimValue = "CanComment" }; var claim3 = new IdentityRoleClaim <string> { ClaimType = "CanEdit", ClaimValue = "CanEdit" }; if (!context.RoleClaims.Any()) { await roleManager.AddClaimAsync(adminRole, claim1.ToClaim()); await roleManager.AddClaimAsync(adminRole, claim3.ToClaim()); await roleManager.AddClaimAsync(userRole, claim2.ToClaim()); } IdentityUser user = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; IdentityUser user1 = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; IdentityUser user2 = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; IdentityUser user3 = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; IdentityUser user4 = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; IdentityUser user5 = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; IdentityUser user6 = new IdentityUser { UserName = "******", Email = "*****@*****.**" }; userManager.CreateAsync(user, "Password123!").Wait(); userManager.CreateAsync(user1, "Password123!").Wait(); userManager.CreateAsync(user2, "Password123!").Wait(); userManager.CreateAsync(user3, "Password123!").Wait(); userManager.CreateAsync(user4, "Password123!").Wait(); userManager.CreateAsync(user5, "Password123!").Wait(); userManager.CreateAsync(user6, "Abc123!").Wait(); await userManager.AddToRoleAsync(user, "admin"); await userManager.AddToRoleAsync(user1, "user"); await userManager.AddToRoleAsync(user2, "user"); await userManager.AddToRoleAsync(user3, "user"); await userManager.AddToRoleAsync(user4, "user"); await userManager.AddToRoleAsync(user5, "user"); await userManager.AddToRoleAsync(user6, "user"); }
public PermissionDto Convert(IdentityRoleClaim <Guid> source, PermissionDto destination, ResolutionContext context) { return(Mapper.Map <PermissionDto>(_claimsService.GetPermissionByValue(source.ClaimValue))); }
public static RoleClaimsDto ToModel(this IdentityRoleClaim <string> roleClaim) { return(Mapper.Map <RoleClaimsDto>(roleClaim)); }
public static Permission Convert(IdentityRoleClaim <string> s) { var tmp = Permissions.GetPermissionByValue(s.ClaimValue); return(tmp); }
internal override IdentityRoleClaim <string> Incluir(IdentityRoleClaim <string> entidade) { throw new NotImplementedException(); }
public async Task Seed() { try { var user1 = await _userMgr.FindByNameAsync("superuser"); var user = await _userMgr.FindByNameAsync("normaluser"); if (user == null) { user = new IdentityUser { UserName = "******", SecurityStamp = Guid.NewGuid().ToString(), }; var result = await _userMgr.CreateAsync(user, "Password@123"); } // Add User var role = await _roleMgr.FindByNameAsync("Admin"); if (role == null) { role = new IdentityRole { Name = "Admin", }; //var roleClaim = new IdentityRoleClaim<string>() { ClaimType = "IsAdmin", ClaimValue = "True" }; //// roleClaim.RoleId = role.Id; //await _roleMgr.CreateAsync(role); //var rd = await _roleMgr.AddClaimAsync(role, new Claim("IsAdmin", "False")); } var roleClaim = new IdentityRoleClaim <string>() { ClaimType = "IsAdmin", ClaimValue = "True" }; // roleClaim.RoleId = role.Id; var rd = await _roleMgr.AddClaimAsync(role, new Claim("IsAdmin", "False")); // var claims =await _roleMgr.GetClaimsAsync(role); var roleResult = await _userMgr.AddToRoleAsync(user1, "Admin"); // var claimResult = await _userMgr.AddClaimAsync(user, new Claim("SuperUser", "True")); var claimResult1 = await _userMgr.AddClaimAsync(user, new Claim("Reader", "True")); var claimResult2 = await _userMgr.AddClaimAsync(user, new Claim("Writer", "True")); //if (!userResult.Succeeded || !roleResult.Succeeded || !claimResult.Succeeded) //{ // throw new InvalidOperationException("Failed to build user and roles"); //} } catch (Exception ex) { } }