简体   繁体   中英

Access Denied for Admin User

I've been trying to add a policy to my admin area of my web app, and have added my admin user and the admin role to both my AspNetUsers , AspNetRoles and AspNetUserRoles tables, however I cannot verify that the user I'm signed is as is an admin.

AspNetUsers table

Id    |    UserName    |    NormalizedUserName    |    Email               |    NormalizedEmail
_______________________________________________________________________________________________
123   |    WebAdmin    |    WEBADMIN              |    admin@mysite.com    |    ADMIN@MYSITE.COM

AspNetRoles Table

Id    |    Name    |    NormalizedName
_______________________________________
123   |    Admin   |    ADMIN
_______________________________________
321   |    User    |    USER

AspNetUserRoles table

UserId    |    RoleId
______________________
123       |    123

I've included the Identity in the ConfirgureServices of my Startup class

/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">Services to configure</param>
public void ConfigureServices(IServiceCollection services)
{
    // Regular Cookie Policy stuff
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    // Mailing service setup
    services.AddScoped<SmtpClient>((serviceProvider) =>
    {
        return new SmtpClient
        {
            Host = this.Configuration.GetValue<string>("Email:Smtp:Host"),
            Port = this.Configuration.GetValue<int>("Email:Smtp:Port"),
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(
                    this.Configuration.GetValue<string>("Email:Smtp:Username"), 
                    this.Configuration.GetValue<string>("Email:Smtp:Password")),
            EnableSsl = true
        };
    });

    // Connect to the Database
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
    services.AddDbContext<WebSiteContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));

    // Identity Stuff
    services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    // Configure Authorization
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Authorization
    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
    });
}

I use all of these in my Configure Method as well

/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">App being configured</param>
/// <param name="env">Environment the app is running in</param>
/// <param name="context">Injected <see cref="DbContext"/></param>
/// <param name="userManager">Injected <see cref="UserManager{TUser}"/></param>
/// <param name="roleManager">Injected <see cref="RoleManager{TRole}"/></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext context, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    // Set up the usings
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication();

    // Seed the Database on Startup
    Seeder.SeedDb(context, userManager, roleManager);

    // Use MVC
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "areas",
            template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

ManageController Controller for my admin portion has the Authorize Declaration

/// <summary>
/// ManageController - Controller for Managing Admin Stuff
/// </summary>
[Area("admin")]
[Route("admin/[controller]")]
[Authorize(Policy = "RequireAdminRole")]
public class ManageController : Controller
{
    /// <summary>
    /// Private instance of the <see cref="EmailViewModel"/> class
    /// </summary>
    private EmailViewModel emailViewModel;
    private SmtpClient smtpClient;

    /// <summary>
    /// Initializes a new instance of the <see cref="ManageController"/> class
    /// </summary>
    /// <param name="smtpClient"></param>
    public ManageController(SmtpClient smtpClient)
    {
        this.smtpClient = smtpClient;
    }


    /// <summary>
    /// HomePage for the admin management area
    /// </summary>
    /// <returns></returns>
    public IActionResult Index()
    {
        return View();
    }
}

However, when I sign in as WebAdmin and navigate to my admin/Manage area, I get the following error:

Access Denied - You do not have access to this resource

Is there something that I'm missing when checking roles in NET Core?

I've solved this issue. The issue lies in configuring the Identity service. I needed to use AddIdentity<IdentityUser, IdentityRole>() instead of AddDefaultIdentity<IdentityUser>()

I changed

// Identity Stuff
services.AddDefaultIdentity<IdentityUser>()
    .AddRoles<IdentityRole>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

To

// Identity Stuff
services.AddIdentity<IdentityUser, IdentityRole>()
    .AddRoles<IdentityRole>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

And it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM