c# - 尽管用户具有正确的角色,但在控制器方法上使用 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);
现在应该是管理员可以编辑系统中的帖子,但它说访问被拒绝。
解决方案
推荐阅读
- angularjs - UI-Router for Angular:是否可以在不重新加载页面的情况下更新位置
- sql-server - 逻辑应用程序 - 从 Web 服务读取 XML 响应并将解析的数据存储在数据库中
- php - 代码 403:“请求缺少有效的 API 密钥。” PERMISSION_DENIED 服务帐号密钥 Google Cloud Vision PHP
- python - 返回该列表中的唯一数字
- spring-mvc - 如何在 webflow 中使用输入/输出元素?
- c# - 根据房间面积创建网格状结构
- zlib - Zstd/Zlib 压缩是双射的吗?
- react-native - Devtools 无法连接到反应本机模拟器
- c++ - 英特尔引脚:与默认工具一起使用时,两次检测“malloc”
- java - 为什么在这个问题中 4-pass 解决方案的性能比 1-pass 解决方案更快?