在 Web 系統開發中,使用者權限控管向來是核心議題。本文分享一套在 Struts 框架下實作細粒度權限控制的實務做法,供各位參考討論。
系統採用經典的 RBAC(Role-Based Access Control)模型:
採用三層映射關係實現靈活授權:
系統開發完成後,所有功能模組資訊寫入持久化儲存(資料庫或配置檔),作為權限判斷基準。
在每個 <action> 節點新增 role 屬性,填入對應模組名稱,建立 Action 與模組的映射關係:
<action path="/user/list" type="com.example.UserListAction" role="user_management" />
建立 user、role、module 三張核心表及其關聯表,實現角色與模組的多對多映射。
繼承 Struts 的 RequestProcessor(若使用 Tiles 需繼承 TilesRequestProcessor),覆寫 processRoles() 方法:
protected boolean processRoles(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) {
// 1. 取得當前 Action 對應的模組名稱
String moduleName = mapping.getRole();
// 2. 從 Session 取得當前使用者角色
User user = (User) request.getSession().getAttribute("currentUser");
Role role = user.getRole();
// 3. 查詢角色是否擁有該模組權限(建議加入快取機制)
boolean hasPermission = permissionCache.hasPermission(role.getId(), moduleName);
if (!hasPermission) {
// 轉向無權限頁面或拋出異常
return false;
}
return true;
}
除基本角色驗證外,可在同一方法中整合:
| 優點 | 缺點 |
|---|---|
| URL 級攔截,即使連結外洩也能阻擋非法存取 | 每次請求皆需判斷,需搭配快取機制緩解效能 |
| 配置集中於 struts-config.xml,維護直觀 | Action 數量龐大時,role 屬性維護成本增加 |
| 擴充性強,易整合 IP、Session 等進階策略 | 僅適用於 Struts 1.x 架構,Struts 2 需改用 Interceptor 實現 |
此方案在中型專案中驗證可行,若專案採用 Spring Security 或 Shiro 等專業安全框架,建議改用標準化方案替代。