如何从 c2WTS 请求令牌

下面的代码示例说明如何向 请求令牌并使用该令牌来模拟用户。 有关详细信息,请参阅 Claims to Windows Token Service (c2WTS) 概述

// Get the current identity and extract the UPN claim. IClaimsIdentity identity = ( ClaimsIdentity )Thread.CurrentPrincipal.Identity; string upn = null; foreach ( Claim claim in identity.Claims ) { if ( StringComparer.Ordinal.Equals( System.IdentityModel.Claims.ClaimTypes.Upn, claim.ClaimType ) ) { upn = claim.Value; } }

// Perform the UPN logon through the c2WTS. WindowsIdentity windowsIdentity = null; if ( !String.IsNullOrEmpty( upn ) ) { try { windowsIdentity = S4UClient.UpnLogon( upn ); } catch ( SecurityAccessDeniedException ) { Console.WriteLine( "Could not map the upn claim to a valid windows identity." ); return; } } else { throw new Exception( "No UPN claim found" ); }

using ( WindowsImpersonationContext ctxt = windowsIdentity.Impersonate() ) { // Access the resource. }

管理员必须为 配置一个允许的调用方列表,其中列出配置文件 c2wtshost.exe.configMicrosoft.IdentityModel 部分中 allowedCallers 元素内的安全标识符 (SID),该配置文件位于 WIF 安装文件夹内的版本文件夹中。 例如,如果将 WIF 3.5 版安装到 C:\Program Files 中,则 c2wtshost.exe.config 文件位于 C:\Program Files\Windows Identity Foundation\v3.5 文件夹中。 示例如下:

<?xml version="1.0"?>

<configuration> <configSections> <section name="windowsTokenService" type="Microsoft.IdentityModel.WindowsTokenService.Configuration.WindowsTokenServiceSection, Microsoft.IdentityModel.WindowsTokenService, Version=0.6.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </configSections>

  <windowsTokenService> <!-- By default no callers are allowed to use the Claims to Windows Token Service. Add the identities you wish to allow below. --> <allowedCallers> <clear/> <!-- <add value="NT AUTHORITY\Network Service" /> --> <!-- <add value="NT AUTHORITY\Local Service" /> --> <!-- <add value="NT AUTHORITY\System" /> --> <!-- <add value="NT AUTHORITY\Authenticated Users" /> --> </allowedCallers> </windowsTokenService> </configuration>