【问题标题】:Asp.net Core MVC Roles and AuthorizationAsp.net Core MVC 角色和授权
【发布时间】:2021-09-04 15:45:31
【问题描述】:

对于一个学校项目,我正在重新制作 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

【问题讨论】:

  • Startup:Configure 方法中有 app.UseAuthenticationapp.UseAuthorization() 吗?
  • 是的,我有这个顺序。我会将其附加到我的问题中。
  • 嗨@Samball,有关于这个案例的最新消息吗?
  • @Yinqiu 现在可以了,谢谢你的帮助!

标签: c# asp.net asp.net-mvc asp.net-core authorization


【解决方案1】:

从你的数据库截图来看,你可能没有成功创建角色,你可以像下面的方法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();

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

【讨论】:

  • 我已经进行了您建议的更改,但是当我查看我的数据库时,没有创建管理员角色。我必须调用 CreateRolesandUsers() 方法吗?在哪里?
  • 可以直接在url中访问方法
  • 我是否特别需要访问该网址?那么 localhost/home/CreateRolesandUsers?因为我试过了,但我得到了一个线程错误。多个线程使用同一个 DbContext 实例。
  • 为什么你的项目中有两个 dbcontexts 使用相同的连接字符串。
  • 你的db_a74225_top2000Context是什么?你的项目中有两个数据库吗?您的哪一个 dbcontexts 继承自 IdentityDbContext
猜你喜欢
  • 1970-01-01
  • 2010-10-21
  • 2020-05-18
  • 2023-03-19
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-03
  • 2020-10-19
相关资源
最近更新 更多