首页 > 解决方案 > 尽管用户具有正确的角色,但在控制器方法上使用 Authorize 注释仍显示“访问被拒绝”

问题描述

我有一个控制器方法,只允许具有 canModify 角色的用户使用。我已确保该用户具有此角色,并且该用户显示为该角色组的成员。但是,当我尝试在此帐户上编辑帖子时,它会显示“拒绝访问”页面。

我不知道从这里去哪里。我已打印出属于当前登录用户的角色,并显示“canModify”。我已经打印出拥有“canModify”角色的用户列表,并且打印出我登录的用户。

Controller 中的 GET Edit 方法:

[Authorize(Roles = "canModify")]
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var post = await _context.Post.FindAsync(id);
        if (post == null)
        {
            return NotFound();
        }
        return View(post);
    }

角色设置的位置:

private async Task Admin(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
    {
        await rm.CreateAsync(new IdentityRole("canModify"));
        ApplicationUser admin = new ApplicationUser
        {
            UserName = "admin@test.com"
        };
        if (context.Users.Where(u => u.UserName == admin.UserName).Count() == 0)
        {
            userManager.CreateAsync(admin, "Password123!").Wait();
            userManager.AddToRoleAsync(admin, "canModify").Wait();
        }
    }

这是我在 Startup.cs 中的配置方法:

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();

var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
DbInitializer dbi = new DbInitializer(roleManager);
dbi.Initialize(context, userManager);

现在应该是管理员可以编辑系统中的帖子,但它说访问被拒绝。

标签: c#asp.net-mvc

解决方案


推荐阅读