Home > Enterprise >  Search for userId to deny access
Search for userId to deny access

Time:06-22

I'm new to mvc and identity framework and I'm struggling to understand how to ban a user with the admin role. I saw videos and tutorials and I keep getting more confused. They all use the identity framework and I'm trying to avoid that and do something more simple and easy to understand. Even following tutorials I keep getting errors when calling the userManager method and I have no idea of what that is and how to instantiate or initialize. I have two databases, one to the project and another to the identity

I have an admin view

<form>
<div >
            <label asp-for="UserId" >User Id: </label>
            <input asp-for="UserId"  />
</div>
<div ><a  asp-action="BanUser">Ban this user</a></div>
</div>
</form>

A controller

public class AdminController : Controller
    {
        private readonly ILogger<AdminController> _logger;

        public AdminController(ILogger<AdminController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public IActionResult BanUser()
        {
            return View();
        }

ApplicationUser class

public class ApplicationUser : IdentityUser
    {
        public virtual Profile? Profile { get; set; }
    }

profile Class

public class Profile
    {
        public int ProfileId { get; set; }

        public string? Name{ get; set; }

        public string? ApplicationUserId { get; set; }

        public virtual ApplicationUser? ApplicationUser { get; set; }
    }

a repository

public static class Repository
    {
      public static List<Profile> Profile
        {
            get
            {
                ApplicationDbContext dataBase = new ApplicationDbContext();
                List<Profile> profiles = dataBase.Profiles.ToList();
                return profiles;
            }
        }

        public static void NewProfile(Profile newProfile)
        {
            ApplicationDbContext dataBase = new ApplicationDbContext();
            dataBase.Profiles.Add(newProfile);
            dataBase.SaveChanges();
        }
}

A profile view model

public class ProfileViewModel
    {
        public Profile newProfile { get; set; }
    }

An ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public ApplicationDbContext() {}

        public DbSet<Profile> Profiles { get; set; }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connection = @"Server=(localdb)\mssqllocaldb;Database=ExerciseDb; Trusted_Connection=True;";
            optionsBuilder.UseLazyLoadingProxies().UseSqlServer(connection);
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.HasDefaultSchema("Identity");
            builder.Entity<IdentityUser>(entity =>
            {
                entity.ToTable(name: "User");
            });
            builder.Entity<IdentityRole>(entity =>
            {
                entity.ToTable(name: "Role");
            });
            builder.Entity<IdentityUserRole<string>>(entity =>
            {
                entity.ToTable("UserRoles");
            });
            builder.Entity<IdentityUserClaim<string>>(entity =>
            {
                entity.ToTable("UserClaims");
            });
            builder.Entity<IdentityUserLogin<string>>(entity =>
            {
                entity.ToTable("UserLogins");
            });
            builder.Entity<IdentityRoleClaim<string>>(entity =>
            {
                entity.ToTable("RoleClaims");
            });
            builder.Entity<IdentityUserToken<string>>(entity =>
            {
                entity.ToTable("UserTokens");
            });

            builder.Entity<ApplicationUser>()
                .HasOne(a => a.Profile)
                .WithOne(p => p.ApplicationUser)
                .HasForeignKey<Profile>(p => p.ApplicationUserId);

            builder.Entity<IdentityRole>().HasData(
                new IdentityRole() { Id = "1", Name = "Admin" },
                new IdentityRole() { Id = "2", Name = "User" }
                new IdentityRole() { Id = "3", Name = "unbanned" }
            );

I found a lot of tutorials like this https://csharp-video-tutorials.blogspot.com/2019/07/add-or-remove-users-from-role-in-aspnet.html but they all have in common something that I can't access, the userManager, others use older versions of asp.net core which make me even more confused that I already am. I'm stuck and the more I read, the less I understand

CodePudding user response:

The First Question, What is the UserManager? UserManager provides the APIs for managing user in a persistence store. UserManager provides alot of methods to Manage users, passwords, profile data, roles, claims, tokens, email confirmation, and more. It's not just database access. It is also code that manages login functionality, secure token creation, secure password management and much more.

In general, UserManager provides developers with a more convenient, efficient and safe choice. You can access this link to check the properties and methods in UserManager.

The Second Question, How to use UserManager? We usually inject it in controller, For Example, If you want to use it in your AdminController, You can follow this code to inject:

public class AdminController : Controller
{
      private readonly UserManager<ApplicationUser> userManager;

      public AdminController(UserManager<ApplicationUser> userManager)
      {
           this.userManager = userManager;
      }

      //then in your action, you can use userManager.xxx to do something.
}

If you want to learn more about identity in Asp.Net Core, I suggest you to follow this tutorial, This tutorial will explian more details about UserManager and other in identity.

  • Related