HOW TO:存取 ASP.NET 頁面內的宣告

Windows® Identity Foundation (WIF) 提供設計階段控制項和 WS-同盟驗證模組 (WS-FAM) 程式設計模型,讓 ASP.NET 開發人員接受來自 ASP.NET 頁面呼叫者的權仗。 這些權仗包含有關呼叫者的資訊,WIF 會將這些資訊當做宣告對開發人員公開。 本主題說明如何存取這些宣告。

存取宣告

若要存取身分識別相關的資訊,您可以執行 FedUtil。 如需相關資訊,請參閱 使用 FedUtil 建立 ASP.NET 信賴憑證者應用程式與 STS 之間的信任。 執行 FedUtil 之後,您的應用程式就可以使用標準的 ASP.NET 結構存取 IClaimsPrincipalIClaimsIdentity,如下列程式碼範例中所示:

void Page_Load(object sender, EventArgs e) { // Cast the Thread.CurrentPrincipal IClaimsPrincipal icp = Thread.CurrentPrincipal as IClaimsPrincipal;

    // Access IClaimsIdentity which contains claims IClaimsIdentity claimsIdentity = (IClaimsIdentity)icp.Identity;
    
    // Access claims foreach(Claim claim in claimsIdentity.Claims) {

    } }

列舉使用者的宣告

一旦擁有 IClaimsIdentity 的存取權,您就可以透過逐一查看宣告集合的方式列舉宣告。 下列程式碼範例示範 WIF 從傳入安全性權仗中擷取的所有宣告屬性 (也就是宣告類型、宣告值和宣告值類型)。 另外,請參閱範例目錄中的<開始使用/簡單宣告感知 Web 應用程式>範例。

注意

請不要在實際執行環境中使用下列範例程式碼。 在實際執行程式碼中,您應仔細考慮對用戶端顯示宣告的屬性會對安全性造成什麼樣的影響。 例如,您應考慮僅接受信賴憑證者應用程式預期的宣告類型、使用宣告屬性前先行處理,以及篩選出包含個人機密資料的宣告。

void Page_Load(object sender, EventArgs e) { // Cast the Thread.CurrentPrincipal IClaimsPrincipal icp = Thread.CurrentPrincipal as IClaimsPrincipal;

    // Access IClaimsIdentity which contains claims IClaimsIdentity claimsIdentity = (IClaimsIdentity)icp.Identity;
    
    // Access claims foreach(Claim claim in claimsIdentity.Claims) { Response.Write(claim.ClaimType) + "<BR>"; Response.Write(claim.Value) + "<BR>"; Response.Write(claim.ValueType) + "<BR>"; } }

存取特定宣告

一旦擁有 IClaimsIdentity 的存取權,您就可以透過在 Claims 集合中尋找指定宣告類型的方式存取特定宣告。 您可以透過逐一查看集合中的宣告或使用 LINQ 的方式執行這項操作。

下列程式碼範例示範如何透過逐一查看集合中的宣告來存取特定宣告。

void Page_Load(object sender, EventArgs e) { // Cast the Thread.CurrentPrincipal IClaimsPrincipal icp = User as IClaimsPrincipal;

    // Access IClaimsIdentity which contains claims IClaimsIdentity claimsIdentity = (IClaimsIdentity)icp.Identity;
    
    // Access claims foreach(Claim claim in claimsIdentity.Claims) { if(claim.ClaimType == "http://GenevaFramework/AgeClaim") { Response.Write("Age Claim: " + claim.Value); break; } } }

下列程式碼範例示範如何使用 LINQ 存取特定宣告。

void Page_Load(object sender, EventArgs e) { // Cast the Thread.CurrentPrincipal IClaimsPrincipal icp = User as IClaimsPrincipal;

    // Access IClaimsIdentity which contains claims IClaimsIdentity claimsIdentity = (IClaimsIdentity)icp.Identity;
    
    // Access claim string ageClaimValue;

    try { ageClaimValue = ( from c in claimsIdentity.Claims where c.ClaimType == "http://GenevaFramework/AgeClaim" select c.Value ).Single(); } catch (InvalidOperationException) { ageClaimValue = "Age claim wasn’t found or " + "there were more than one Age claims provided"; }

    Response.Write("Age Claim: " + ageClaimValue); }