How to: Request a Token from the c2WTS

[Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework. The version of WIF addressed by this topic, WIF 3.5, is deprecated and should only be used when developing against the .NET Framework 3.5 SP1 or the .NET Framework 4. For more information about WIF in the .NET Framework 4.5, also known as WIF 4.5, see the Windows Identity Foundation documentation in the .NET Framework 4.5 Development Guide.]

The following code sample shows how to request a token from the Claims to Windows Token Service (c2WTS) and use it to impersonate the user. For more information, see Claims to Windows Token Service (c2WTS) Overview.

// 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.
}

An administrator must configure the c2WTS with a list of allowed callers, which is the list of security identifiers (SIDs) in the allowedCallers element in the Microsoft.IdentityModel section of the configuration file c2wtshost.exe.config, located in the version folder inside your WIF installation folder. For example, if you installed version 3.5 of WIF to C:\Program Files, the c2wtshost.exe.config file is located in the C:\Program Files\Windows Identity Foundation\v3.5 folder. An example follows:

<?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>