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

Geneva 框架(WIF)打造宣告式 WCF 服務完整指南

     編輯:關於.NET

為何需要宣告式安全?

傳統角色型授權將應用程式綁定特定角色群組。宣告式模型以「宣告」為核心,解耦身分驗證與授權邏輯,支援多種認證來源(Windows、UserName、憑證、SAML Token)並利於聯合身分場景。

核心架構:STS 與信任鏈

  • STS (Security Token Service):驗證使用者並簽發含宣告的 SAML Token。
  • 信賴憑證者:WCF 服務或 ASP.NET 應用,信任 STS 簽章,據以授權。
  • 聯合:跨域信任,使用者僅向自屬域驗證,取得 Token 存取他域資源。

Geneva 框架簡化 WCF 宣告處理

傳統 WCF 需手動遍歷 AuthorizationContext

var authCtx = ServiceSecurityContext.Current.AuthorizationContext;
foreach (var cs in authCtx.ClaimSets)
    if (cs.ContainsClaim(new Claim(..., "Delete", Rights.PossessProperty))) ...

啟用 Geneva 後:ClaimsPrincipal 直接掛載於 Thread.CurrentPrincipal

// 設定 ServiceHost
var host = new ServiceHost(typeof(RelyingParty));
FederatedServiceCredentials.ConfigureServiceHost(host, new TrustedIssuerNameRegistry());
host.Open();

授權寫法大幅簡化

[PrincipalPermission(SecurityAction.Demand,
    Role = "https://schemas.contoso.com/.../permission/Delete")]
public string DeleteSomething() { ... }

// 或程式碼檢查
if (!Thread.CurrentPrincipal.IsInRole(".../permission/Delete"))
    throw new SecurityException("Access denied");

關鍵設定:<microsoft.identityModel>

<microsoft.identityModel>
  <issuerNameRegistry type="Services.TrustedIssuerNameRegistry, Services" />
  <securityTokenHandlers>
    <remove type="Microsoft.IdentityModel.Tokens.Saml11.Saml11SecurityTokenHandler, ..." />
    <add type="Microsoft.IdentityModel.Tokens.Saml11.Saml11SecurityTokenHandler, ...">
      <samlSecurityTokenRequirement audienceUriMode="Never">
        <nameClaimType value="https://schemas.contoso.com/ws/2005/05/claims/name" />
        <roleClaimTypes>
          <add value="https://schemas.contoso.com/.../claims/permission" />
        </roleClaimTypes>
      </samlSecurityTokenRequirement>
    </add>
  </securityTokenHandlers>
</microsoft.identityModel>

自訂 roleClaimType 為權限宣告,即可沿用 PrincipalPermission 屬性進行細粒度授權。

IIS 託管啟用方式

自訂 ServiceHostFactory,於 InitializeRuntime 呼叫 FederatedServiceCredentials.ConfigureServiceHost,並在 .svc 指定 Factory 屬性。

遷移既有 WCF 宣告式服務

  • 移除自訂 IAuthorizationPolicy,改用 Geneva 內建 ServiceAuthorizationPolicy。
  • 授權邏輯從 AuthorizationContext 改為 ClaimsPrincipal。
  • 受益:統一 WCF/ASP.NET 程式模型、新執行緒自動流動身分、支援經典 PrincipalPermission。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved