Asp.net-Core

.net 核心身份 2.1 角色授權不起作用

  • January 23, 2022

在 2.1 之前,我已經多次實施基於角色的身份驗證。按照步驟搭建新的 2.1 標識。

我擴展了 IdentityUser 模型以添加其他欄位,登錄工作正常,新欄位出現。

startup.cs 配置服務包含

        services.AddDefaultIdentity<AppUser>()
           .AddRoles<IdentityRole>()
           .AddEntityFrameworkStores<ApplicationDbContext>();

我播種了角色

        IdentityRole role = new IdentityRole();
        role.Name = "Administrator";
        IdentityResult roleResult = roleManager.
        CreateAsync(role).Result;

然後創建一個使用者並添加到角色

       AppUser user = new AppUser();
       user.UserName = "Admin";
       user.Email = "admin@admin.com";
       user.Name = "Administrator";
       user.LockoutEnabled = false;
       user.EmailConfirmed = true;

       IdentityResult result = userManager.CreateAsync(user, "password").Result;

       if (result.Succeeded)
       {
           userManager.AddToRoleAsync(user, "Administrator").Wait();
       }

一切都成功了,數據庫看起來很好(AspNetUserRoles 有連結)

但是,使用角色裝飾控制器將始終返回未授權

      [Authorize(Roles = "Administrator")]

[Authorize]但是,使用(無角色)的簡單登錄檢查將起作用。

我該如何解決這個問題/合併原始碼的最簡單方法是什麼,以便我可以單步執行/調試[Authorize]標籤?

怎麼修

但是,使用角色裝飾控制器將始終返回未授權

  [Authorize(Roles = "Administrator")]

這是版本中的一個已知錯誤2.1。請參閱此處的問題

我遵循使用 HaoK 和 C-BERBER 建議的舊 api 的建議,它現在可以完美執行。

這是我的DbContext

public class ApplicationDbContext : IdentityDbContext<AppUser,IdentityRole,string>
{
   public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
       : base(options)
   {
   }
}

使用舊式 api 配置身份:

services.AddIdentity<AppUser, IdentityRole>()
       .AddRoleManager<RoleManager<IdentityRole>>()
       .AddDefaultUI()
       .AddDefaultTokenProviders()
       .AddEntityFrameworkStores<ApplicationDbContext>();

最後,註銷並重新登錄,它現在將按預期工作。

如何調試原始碼

我猜你不想調試它AuthorizeAttribe本身,因為它是在編譯時處理的。如果您要調試AuthorizeFilter,可以按照以下步驟操作:

點擊Tools-> Options->Debugging

  1. General取消選擇Enable Just My CodeVisual Studio
  2. 選擇Enable Source Link Support
  3. 在 中Symbols,確保選擇了Microsoft Symbol Servers

你現在可以調試原始碼了。但是,由於過濾器的工作方式,您需要在 MVC 之前設置一個斷點。我只是設置了一個虛擬中間件,它將在 MVC 路由器處理程序之前發生:

在此處輸入圖像描述

調試截圖AuthorizeFiler

在此處輸入圖像描述

引用自:https://stackoverflow.com/questions/52526186