locked
How can I verify a user's role when they log in using identity RRS feed

  • Question

  • User-1314654757 posted

    Good morning to all the members of the forum, greeting to all.  

    How can I verify a user's role when they log in using Identity? First step register Second step, login, but when I try to access a view with "Admin" permissions, it says "Access denied. You do not have access to this resource."

    [Authorize(Roles = "Admin")]
    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";
    
        return View();
    }
    //DBContext
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore;
    
    
    namespace test.Models
    {
        public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() });
                modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "User", NormalizedName = "User".ToUpper() });
                base.OnModelCreating(modelBuilder);
            }
            public DbSet<Test> Test { get; set; }
        }
    }
    

    //

    //Startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        //DataBase Connection
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
    
        // Library Identity
        services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();
        // IdentityOptions
        services.Configure<IdentityOptions>(options =>
        {
            // Default SignIn settings.
            options.SignIn.RequireConfirmedEmail = false;
            options.SignIn.RequireConfirmedPhoneNumber = false;
            // Password settings.
            options.Password.RequireDigit = false;
            options.Password.RequireLowercase = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequiredLength = 4;
            options.Password.RequiredUniqueChars = 0;
    
            // Lockout settings.
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 5;
            options.Lockout.AllowedForNewUsers = true;
    
            // User settings.
            options.User.AllowedUserNameCharacters =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
            options.User.RequireUniqueEmail = false; //
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
    
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication(); //  Use Authentication
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    // Register.cs
            public async Task<IActionResult> OnPostAsync(string returnUrl = null)
            {
                returnUrl = returnUrl ?? Url.Content("~/");
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
                    var result = await _userManager.CreateAsync(user, Input.Password);
                    if (result.Succeeded)
                    {
                        var UserRole = "Admin"; // Admin Role
                        var x = await _userManager.AddToRoleAsync(user, UserRole); // Assignment of the role to the registered user
                        _logger.LogInformation("User created a new account with password.");
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
    
                // If we got this far, something failed, redisplay form
                return Page();
            }

    Sunday, July 14, 2019 3:23 PM

All replies

  • User711641945 posted

    Hi AllukaCode,

    First step register Second step, login, but when I try to access a view with "Admin" permissions, it says "Access denied. You do not have access to this resource."

    It is a known debug in .net core 2.1 .You could refer to: https://github.com/aspnet/Identity/issues/1813

    So you need to configure the identity as below by using AddIdentity to deal reintegrating:

    // Library Identity
    //services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>()
    //        .AddEntityFrameworkStores<ApplicationDbContext>();
    
    services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddDefaultUI()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<ApplicationDbContext>();
    

    Monday, July 15, 2019 5:39 AM
  • User-2054057000 posted

    You have Admin Roles, first check in the database if the Admin role is created in the database table correctly or not. 

    In the C# you can also get all the roles of your application from this code:

    RoleManager<IdentityRole> roleManager;
    public RoleController(RoleManager<IdentityRole> roleMgr)
            {
                roleManager = roleMgr;
            }
    
    var yourRoles = roleManager.Roles;

    Note: here RoleManager will be injected by Dependency Injection feature. 

    Also try deleting roles from your application once more and create them from the beginning. The delete roles code will be:

    IdentityRole role = await roleManager.FindByIdAsync(roleId);
    IdentityResult result = await roleManager.DeleteAsync(role);

    Then when you login, use Incognito window so that the cookies do not interfere in any way.

    If you still get the problem, provide us with the error message which comes up. 

    You can also refer: How to work with Roles in Identity System in ASP.NET Core tutorial which covers Roles topic of Identity.

     

    Tuesday, July 16, 2019 5:27 AM