首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Enterprise Library 實戰系列(五):安全性應用程式區塊——入門篇

     編輯:關於.NET

一、概述

安全性應用程式區塊透過一或多個安全機制,協助開發人員實作通用安全任務,支援擴展性(不修改程式碼切換驗證/授權方式),功能涵蓋:驗證、授權、角色管理、Profile 管理。

二、核心概念

Credential(認證憑證)
證明身分的憑據(如使用者名稱/密碼)
Identity(身分)
代表使用者的身分資訊
Principal(主體)
包含身分與角色的安全主體

三、使用三部曲

前提:專案有 App.config/Web.config,資料庫已建立相關資料表與預存程序(參考 EntLibQuickStarts 範例資料庫)。

1. 定義組態檔

  1. 開啟組態工具,載入專案組態檔
  2. 新增 Security Application Block
  3. Authentication 節點新增 Database Authentication Provider
  4. 設定資料庫連線字串(參考資料存取區塊)
  5. Cryptography 區塊新增 Hash Algorithm Provider,設定 SaltEnabled=True
  6. Authentication Provider 設定 Database=Database Instance、HashProvider=SHA1Managed
  7. Security Block 設定 DefaultAuthenticationInstance=Database Provider
    驗證設定
  8. Roles 節點新增 Role Database Provider,設定 Database=Database Instance
  9. Security Block 設定 DefaultRolesInstance=RolesDatabase Provider
    角色設定
  10. 儲存全部、複製組態檔

2. 建立 Security Provider 實例

IAuthenticationProvider authprovider = AuthenticationFactory.GetAuthenticationProvider();

3. 執行驗證與角色載入

public static bool Authenticate(string username, string password)
{
    bool authenticated = false;
    NamePasswordCredential credentials = new NamePasswordCredential(username, password);
    IAuthenticationProvider authprovider = AuthenticationFactory.GetAuthenticationProvider();
    IIdentity identity;
    authenticated = authprovider.Authenticate(credentials, out identity);
    if (!authenticated) throw new SecurityException("Invalid username or password.");

    IRolesProvider rolesprovider = RolesFactory.GetRolesProvider();
    IPrincipal principal = rolesprovider.GetRoles(identity);
    Thread.CurrentPrincipal = principal; // 關鍵:設定當前執行緒主體
    return authenticated;
}

結語

入門篇完成驗證與角色基本設定。進階篇將深入驗證/授權細節、授權規則、角色策略、個人化服務、嚴格帳號管理、Security Cache 及第三方資料庫角色外掛。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved