在ASP.NET CORE中使用組件屬性定義權限

Likol Lee
Likol Lee
Nov 5 · 3 min read

前言

在過往的網站開發專案中,對我來說權限的定義一直是一個困擾的功能,最常使用的方法是在資料庫中根據開發的功能將權限定義寫入,當需要設定使用者權限時,再由資料庫讀取出來。

用資料庫來存放這些資訊其實已經是個不錯的方式,但是如果網站的功能時常新增或是調整,自然也就需要額外的成本進行維護。

Assembly Attribute

在研究ASP.NET CORE的過程中,經常可以發現使用Assembly Attribute來進行網站啟動的載入作業。

如果可以透過這種方式來定義權限資訊,除了可以省去在資料庫中儲存這些資訊,一方面更可以做到系統載入哪些組件就會自動建立權限資訊。

實作

首先我新增了用來定義權限的類別AccessRightDefinitionAttribute,在每一個組件中允許多個項目。

AccessRightManager

透過AppDomain可以知道目前載入系統中的組件有哪些,進而取得每一個組件中所定義的AccessRightDefinition。

NavigationManager

目前我都是採用RazorPages來進行開發,因此經由ApplicationPartManager與IActionDescriptorCollectionProvider就可以取得目前系統中可以存取的頁面路徑有哪些,接著從RazorPage的Model上,取得與AccessRightDefinitionAttribute的關聯。

透過上述的兩個功能,就可以對應出完整的權限定義資訊。

[其他文章]

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade