Asp.net 核心 MVC 角色和授权

Asp.net Core MVC Roles and Authorization

为了一个学校项目,我正在重建 Top2000 网站(荷兰网站,每年有 2000 首最受欢迎的歌曲)。现在我对角色和授权有疑问。

我想添加一个管理员角色,并且只允许具有该角色的用户访问隐私页面。 这是我到目前为止得到的: Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            
            services.AddDbContext<db_a74225_top2000Context>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }

HomeController.cs

namespace Top2000.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

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

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

        [Authorize(Roles = "Admin")]
        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 });
        }
    }
}

Screenshot of dbo.AspNetUserRoles

Screenshot of dbo.AspNetUsers

Screenshot of dbo.AspNetRoles

我希望进入隐私页面,但当我登录时,我仍然看到访问被拒绝。

Screenshot of Access denied page

从你的数据库截图来看,你可能没有成功创建角色,你可以像下面的方法那样创建一个有角色的用户CreateRolesandUsers.

public class HomeController : Controller
{
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly UserManager<IdentityUser> _userManager;
    public HomeController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
    {
        _roleManager = roleManager;
        _userManager = userManager;
    }
    public async Task CreateRolesandUsers()
    {

        bool x = await _roleManager.RoleExistsAsync("Admin");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Admin";
            await _roleManager.CreateAsync(role);
        }
        var user = new IdentityUser();
        user.UserName = "123@123.com";
        user.Email = "123@123.com";
        string password = "Defaultpassword01!";

        IdentityResult chkUser = await _userManager.CreateAsync(user, password);

        if (chkUser.Succeeded)
        {
            var result = await _userManager.AddToRoleAsync(user, "Admin");
        }
    }
    public IActionResult Index()
    {
        return View();
    }
    [Authorize(Roles = "Admin")]
    public IActionResult Privacy()
    {
        return View();
    }
}

您的 DbContext:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

然后在启动时更改代码

 services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultUI()
                .AddDefaultTokenProviders();

当您访问此方法成功创建角色后,您可以登录用户,然后访问隐私。