locked
What is the direct way to setup Authorization Roles in MVC? RRS feed

  • Question

  • User2142845853 posted

    [Authorize(Roles="Administrators")]

    Can this subject be explained directly?  Without 500 pages of details on how authorization worked in 1997 and the inner if/then/else mechanism of each abstract method in some authorization code?   

    fred1234 admin

    julie9876  admin

    john4567  user

    squiggy 4567  guest

    clearly I need to add a field to the table of users to store the name of the role.  Does it need to just store the role name?  "Administrator" or "admin" or "user", does it need to store a hash of something else? 

    I just want a simple mechanism to authorize users.  there is no explanation thats direct and to the point.  its a zillion pages of blather and code snippets that have no direct meaning.   

    I have read articles by Jon Galloway and Rick Anderson, and other articles, blogs, notes.  

    how to just make a direct authorization scheme?

    I know that if the user (per the system) is a string literal of  "Fred123" or "Jane456" I want the code to be hardwired with the username for my Administrator role

    IAdministrationRoleAssignmentManagerMethod a = new IAdministrationRoleAssignmentManagerMethod ();

    a.Add("Fred123", "Administrator");

    a.Add("Jane123", "SuperUser");

    thats it.  end.   if the system does an [Authorize(roles="Administrator")]  then if Fred123 is the user it will let him pass.  if not?  login fails.

    Why can it not be this simple?

    Monday, June 6, 2016 7:53 PM

All replies

  • User-271186128 posted

    Hi rogersbr,

    What is the direct way to setup Authorization Roles in MVC?

    As for this issue, I suggest you could refer to the following articles:

    http://www.codeproject.com/Articles/799571/ASP-NET-MVC-Extending-ASP-NET-Identity-Roles

    http://www.dotnetcurry.com/aspnet-mvc/1102/aspnet-mvc-role-based-security

    http://www.codeproject.com/Articles/727054/ASP-NET-MVC-Identity-Extending-and-Modifying-R

    Best regards,
    Dillion

    Tuesday, June 7, 2016 5:38 AM
  • User2142845853 posted

    hi Dillion

    Thanks for the reply.  many days now working thru this.  I had been reading thru one link there;  I know its a free article but had to pause when reading this

    DbContext is the glue what sticks your application to the database. It should be well taken care of. My one is a bit clumsy though. Why don't you try to make yours beautiful? I included my DbContext initializer, my seeding mechanism and

    it seems easier to manually create authorization roles.  just skim thru this and see which part IS included in the package and what was added in?  why is there never an explanation thats direct and to the point?  maybe nobody knows how this works.  When trying to find a source online to know how to set it up, trying to get to the point, I get code with no explanation that looks like this:

    using ASPNetMVCExtendingIdentity2Roles.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    
    namespace ASPNetMVCExtendingIdentity2Roles.Context
    {
        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public DbSet<ApplicationRole> Roles { get; set; }
            public ApplicationDbContext()
                : base("DefaultConnection", throwIfV1Schema: false)
            {
            }
    
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                if (modelBuilder == null)
                {
                    throw new ArgumentNullException("ModelBuilder is NULL");
                }
    
                base.OnModelCreating(modelBuilder);
    
                //Defining the keys and relations
                modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
                modelBuilder.Entity<ApplicationRole>().HasKey<string>(r => r.Id).ToTable("AspNetRoles");
                modelBuilder.Entity<ApplicationUser>().HasMany<ApplicationUserRole>((ApplicationUser u) => u.UserRoles);            
                modelBuilder.Entity<ApplicationUserRole>().HasKey(r => new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");            
            }
    
            public bool Seed(ApplicationDbContext context)
            {
    #if DEBUG
                bool success = false;
    
                ApplicationRoleManager _roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context));
                
                success = this.CreateRole(_roleManager, "Admin", "Global Access");
                if (!success == true) return success;
    
                success = this.CreateRole(_roleManager, "CanEdit", "Edit existing records");
                if (!success == true) return success;
    
                success = this.CreateRole(_roleManager, "User", "Restricted to business domain activity");
                if (!success) return success;
    
                // Create my debug (testing) objects here
    
                ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
    
                ApplicationUser user = new ApplicationUser();
                PasswordHasher passwordHasher = new PasswordHasher();
    
                user.UserName = "youremail@testemail.com";
                user.Email = "youremail@testemail.com";
    
                IdentityResult result = userManager.Create(user, "Pass@123");
    
                success = this.AddUserToRole(userManager, user.Id, "Admin");
                if (!success) return success;
    
                success = this.AddUserToRole(userManager, user.Id, "CanEdit");
                if (!success) return success;
    
                success = this.AddUserToRole(userManager, user.Id, "User");
                if (!success) return success;
    
                return success;
    #endif
            }
    
            public bool RoleExists(ApplicationRoleManager roleManager, string name)
            {
                return roleManager.RoleExists(name);
            }
    
            public bool CreateRole(ApplicationRoleManager _roleManager, string name, string description = "")
            {            
                var idResult = _roleManager.Create<ApplicationRole, string>(new ApplicationRole(name, description));
                return idResult.Succeeded;
            }
    
            public bool AddUserToRole(ApplicationUserManager _userManager, string userId, string roleName)
            {
                var idResult = _userManager.AddToRole(userId, roleName);
                return idResult.Succeeded;
            }
    
            public void ClearUserRoles(ApplicationUserManager userManager, string userId)
            {
                var user = userManager.FindById(userId);
                var currentRoles = new List<IdentityUserRole>();
    
                currentRoles.AddRange(user.UserRoles);
                foreach (ApplicationUserRole role in currentRoles)
                {
                    userManager.RemoveFromRole(userId, role.Role.Name);
                }
            }
    
            public void RemoveFromRole(ApplicationUserManager userManager, string userId, string roleName)
            {
                userManager.RemoveFromRole(userId, roleName);
            }
    
            public void DeleteRole(ApplicationDbContext context, ApplicationUserManager userManager, string roleId)
            {
                var roleUsers = context.Users.Where(u => u.UserRoles.Any(r => r.RoleId == roleId));
                var role = context.Roles.Find(roleId);
    
                foreach (var user in roleUsers)
                {
                    this.RemoveFromRole(userManager, user.Id, role.Name);
                }
                context.Roles.Remove(role);
                context.SaveChanges();
            }
    
            /// <summary>
            /// Context Initializer
            /// </summary>
            public class DropCreateAlwaysInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
            {
                protected override void Seed(ApplicationDbContext context)
                {
                    context.Seed(context);
    
                    base.Seed(context);
                }
            }
        }    
    }

    am still trying to grasp what this is doing, what is needed, what isnt.    clearly no direct and clear method to set authorization roles.  will keep on trying and searching online

    Zhi Lv - MSFT

    Hi rogersbr,

    rogersbr

    What is the direct way to setup Authorization Roles in MVC?

    As for this issue, I suggest you could refer to the following articles:

    http://www.codeproject.com/Articles/799571/ASP-NET-MVC-Extending-ASP-NET-Identity-Roles

    http://www.dotnetcurry.com/aspnet-mvc/1102/aspnet-mvc-role-based-security

    http://www.codeproject.com/Articles/727054/ASP-NET-MVC-Identity-Extending-and-Modifying-R

    Best regards,
    Dillion

    Tuesday, June 7, 2016 5:52 PM
  • User2142845853 posted

    http://www.codeproject.com/Articles/799571/ASP-NET-MVC-Extending-ASP-NET-Identity-Roles   this one has MISSING CODE in the example.  the guy even says he got it from someone else

    Tuesday, June 7, 2016 6:41 PM