Wednesday, August 31, 2011

The quest for customizing ADFS sign-in web pages, part 2 – a custom STS

The quest for customizing ADFS sign-in web pages starts with writing a custom STS. The plan is as follows:

  1. Write a custom STS
  2. Test the STS with any RP application
  3. Federate ADFS with the STS

The aim of this post is the first task from this list.

Writing a custom STS

The custom STS basically consist of two web pages – the first one should be responsible for authentication and the second for dealing with WS-Federation login requests and SAML responses.

The basic structure

Which authentication method you choose is up to you. What’s important is to be able to authenticate a user only once and then store the information somewhere so that when consecutive requests from other RPs hit your STS, the user does not have to authenticate again. For example then, the well known Forms Authentication is a good choice for a custom STS.

Create two web pages, LoginPage.aspx and Default.aspx. Leave Default.aspx empty for now and make the LoginPage.aspx an actual login page – set authentication to Forms in web.config, add the <authorization> section so that all unauthenticated requests are redirected to Login.aspx and plug a MembershipProvider of your choice to the pipeline.

After you are done, let’s move to the next step.

Federation metadata

To become an STS, your application should provide a metadata for RP applications. Metadata makes the federation easier, you do not input all settings manually but you can use some authomated tools like the fedutil.exe (=”Add STS Reference” from VS).

In your project, create a folder FederationMetadata and a subfolder 2007-06 in it. This is only a convention but we will follow it. In the subfolder, create FederationMetadata.ashx handler – we will create the metadata dynamically. Also create a local web.config file with authorization set to “allow users=*” – you’d like your metadata to be available for everyone, not only for users who first log into your STS.

The metadata handler code is a copy-paste from one of the WIF SDK examples (remember to first add references to “Microsoft.IdentityModel” and “System.IdentityModel”):

public class FederationMetadata : IHttpHandler
 {
     public void ProcessRequest( HttpContext context )
     {
         MetadataBase metadata = Common.GetFederationMetadata();
         MetadataSerializer serializer = new MetadataSerializer();
         serializer.WriteMetadata( context.Response.OutputStream, metadata );
         context.Response.ContentType = "text/xml";
     }
 
     public bool IsReusable
     {
         get
         {
             return true;
         }
     }
 }

As you can see, we delegate the metadata creation to another class, Common, and then simply serialize the metadata and write to the output stream. Metadata provide the information about the STS itself, like it’s endpoints, the signing certificate or the list of offered claims. Most of these are straightforward except the certificate – you have to create it and then import to your application.

I prefer to use Portecle to create certificates, just run the application, create new PKCS#12 keystore, generate a new RSA key pair and save the keystore to a .pfx file (you’ll have to provide a password like “12345678”).

Now we write some code to import certificates from *.pfx files dynamically (without manually importing certificates to the keystore). Since we’ll import the certificate from the assembly resources, remember to add it to your project and set it to be an embedded resource.

public class CertificateUtil
{
    static Dictionary<string, X509Certificate2> _certificates = 
        new Dictionary<string, X509Certificate2>();
 
    public static X509Certificate2 GetCertificate( 
        string CertResourceName, 
        string CertPwd )
    {
        if ( !_certificates.ContainsKey( CertResourceName ) )
        {
            foreach ( string name in 
                typeof( CertificateUtil ).Assembly.GetManifestResourceNames() )
                if ( name.EndsWith( CertResourceName ) )
                {
                    Stream certificateStream = 
                        typeof( CertificateUtil ).Assembly.GetManifestResourceStream( name );
 
                    using ( BinaryReader br = new BinaryReader( certificateStream ) )
                        _certificates[CertResourceName] = 
                            new X509Certificate2( br.ReadBytes( (int)certificateStream.Length ), 
                                CertPwd, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable );
                }
        }
 
        if ( _certificates.ContainsKey( CertResourceName ) )
            return _certificates[CertResourceName];
 
        throw new Exception( "No certificate was found in application's resources" );
    }
}

Now back to our Metadata generation class:

/// <summary>
 /// Summary description for Common
 /// </summary>
 public static class Common
 {
     /// <summary>
     /// Metadane usługi federacyjnej
     /// </summary>
     public static MetadataBase GetFederationMetadata()
     {
         string endpointId = UriHelper.ResolveServerUrl( "~/Default.aspx" );
         EntityDescriptor metadata = new EntityDescriptor();
         metadata.EntityId = new EntityId( endpointId );
 
         // Define the signing key
         X509Certificate2 cert = 
             CertificateUtil.GetCertificate( "the.custom.sts.pfx", "12345678" );
         metadata.SigningCredentials = new X509SigningCredentials( cert );
 
         // Create role descriptor for security token service
         SecurityTokenServiceDescriptor stsRole = new SecurityTokenServiceDescriptor();
         stsRole.ProtocolsSupported.Add( new Uri( WSFederationMetadataConstants.Namespace ) );
         metadata.RoleDescriptors.Add( stsRole );
 
         // Add a contact name
         ContactPerson person = new ContactPerson( ContactType.Administrative );
         person.GivenName = "contactName";
         stsRole.Contacts.Add( person );
 
         // Include key identifier for signing key in metadata
         SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause( cert );
         SecurityKeyIdentifier ski = new SecurityKeyIdentifier( clause );
         KeyDescriptor signingKey = new KeyDescriptor( ski );
         signingKey.Use = KeyType.Signing;
         stsRole.Keys.Add( signingKey );
 
         // Add endpoints
         string activeSTSUrl   = 
             UriHelper.ResolveServerUrl( "~/Default.aspx" );
         string activeMetadata = 
             UriHelper.ResolveServerUrl( "~/FederationMetadata/2007-06/FederationMetadata.ashx" );
         EndpointAddress endpointAddress = new EndpointAddress(
                                                 new Uri( activeSTSUrl ),
                                                 null,
                                                 null,
                                                 GetMetadataReader( activeMetadata ), null );
         stsRole.SecurityTokenServiceEndpoints.Add( endpointAddress );
 
         // offer two claims
         stsRole.ClaimTypesOffered.Add( new DisplayClaim( ClaimTypes.Name ) );
         stsRole.ClaimTypesOffered.Add( new DisplayClaim( ClaimTypes.Role ) );
 
         return metadata;
     }
 
     /// <summary>
     /// Create a reader to provide simulated Metadata endpoint configuration element
     /// </summary>
     /// <param name="activeSTSUrl">The active endpoint URL.</param>
     static XmlDictionaryReader GetMetadataReader( string activeSTSUrl )
     {
         MetadataSet metadata = new MetadataSet();
         MetadataReference mexReferece = 
             new MetadataReference( 
                 new EndpointAddress( activeSTSUrl + "/mex" ), 
                 AddressingVersion.WSAddressing10 );
         MetadataSection refSection = 
             new MetadataSection( MetadataSection.MetadataExchangeDialect, null, mexReferece );
         metadata.MetadataSections.Add( refSection );
 
         byte[] metadataSectionBytes;
         StringBuilder stringBuilder = new StringBuilder();
         using ( StringWriter stringWriter = new StringWriter( stringBuilder ) )
         {
             using ( XmlTextWriter textWriter = new XmlTextWriter( stringWriter ) )
             {
                 metadata.WriteTo( textWriter );
                 textWriter.Flush();
                 stringWriter.Flush();
                 metadataSectionBytes = 
                     stringWriter.Encoding.GetBytes( stringBuilder.ToString() );
             }
         }
 
         return XmlDictionaryReader.CreateTextReader( 
             metadataSectionBytes, 
             XmlDictionaryReaderQuotas.Max );
     }

Few things here to notice.

First, we import the certificate from the *.pfx file and we have to provide this “12345678” password to import both keys. Then we use a little helper by Rick Strahl to be able to resolve uris. Then we describe the endpoints and offered claims. Our metadata is ready, you can open your browser and point it to http://whatever.your.address.is/FederationMetadata/2007-06/FederationMetadata.ashx.

After you are done, let’s move to the next step.

Handling WS-Federation requests and responses

To handle actucal WS-Federation requests from RP applications you need a custom token service. Let’s start from the token service configuration:

/// <summary>
/// A custom SecurityTokenServiceConfiguration implementation.
/// </summary>
public class CustomSecurityTokenServiceConfiguration : 
    SecurityTokenServiceConfiguration
{
    static readonly object syncRoot = new object();
    const string CustomSTSKey = "CustomSTS.key";
 
    public static CustomSecurityTokenServiceConfiguration Current
    {
        get
        {
            HttpApplicationState httpAppState = HttpContext.Current.Application;
 
            CustomSecurityTokenServiceConfiguration customConfiguration = 
                httpAppState.Get( CustomSTSKey ) 
                as CustomSecurityTokenServiceConfiguration;
 
            if ( customConfiguration == null )
            {
                lock ( syncRoot )
                {
                    customConfiguration =
                        httpAppState.Get( CustomSTSKey ) 
                        as CustomSecurityTokenServiceConfiguration;
 
                    if ( customConfiguration == null )
                    {
                        customConfiguration = 
                            new CustomSecurityTokenServiceConfiguration();
                        httpAppState.Add( CustomSTSKey, customConfiguration );
                    }
                }
            }
 
            return customConfiguration;
        }
    }
 
    /// <summary>
    /// CustomSecurityTokenServiceConfiguration constructor.
    /// </summary>
    public CustomSecurityTokenServiceConfiguration()
        : base( "The.Custom.STS",
                new X509SigningCredentials( 
                    CertificateUtil.GetCertificate( "the.custom.sts.pfx", "12345678" ) )
               )
    {
        this.SecurityTokenService = typeof( CustomSecurityTokenService );
    }
}

And the token service itself:

/// <summary>
 /// A custom SecurityTokenService implementation.
 /// </summary>
 public class CustomSecurityTokenService : SecurityTokenService
 {
     public CustomSecurityTokenService( SecurityTokenServiceConfiguration configuration )
         : base( configuration )
     {
     }
 
     void ValidateAppliesTo( EndpointAddress appliesTo )
     {
         if ( appliesTo == null )
         {
             throw new ArgumentNullException( "appliesTo" );
         }
     }
 
     protected override Scope GetScope( 
         IClaimsPrincipal principal, 
         RequestSecurityToken request )
     {
         ValidateAppliesTo( request.AppliesTo );
 
         Scope scope = new Scope( 
             request.AppliesTo.Uri.OriginalString, 
             SecurityTokenServiceConfiguration.SigningCredentials );
         scope.TokenEncryptionRequired = false;
 
         scope.ReplyToAddress = scope.AppliesToAddress;
         //scope.ReplyToAddress = request.ReplyTo;
 
         return scope;
     }
 
 
     protected override IClaimsIdentity GetOutputClaimsIdentity( 
         IClaimsPrincipal principal, 
         RequestSecurityToken request, Scope scope )
     {
         if ( null == principal )
         {
             throw new ArgumentNullException( "principal" );
         }
 
         ClaimsIdentity outputIdentity = new ClaimsIdentity();
 
         // Name
         outputIdentity.Claims.Add( new Claim( ClaimTypes.Name, principal.Identity.Name ) );
 
         // Roles (should be dynamic)
         outputIdentity.Claims.Add( new Claim( ClaimTypes.Role, "Role1" ) );
         outputIdentity.Claims.Add( new Claim( ClaimTypes.Role, "Role2" ) );
 
         return outputIdentity;
     }
 }

As you can see, the configuration uses the certificate we’ve created eariler (yet again we have to provide the password) and the token service transforms the existing principal (which is the Forms Identity because of the way we’ve chosen users are authenticated) to the ClaimsIdentity – the object can contain arbitrary claims, including the Name, Roles, Givenname, Surname, Email etc.

The remaining thing is the code of the WS-Federation request/response processor which in our case is the Default.aspx page:

public partial class Default : System.Web.UI.Page
{
    /// <summary>
    /// Performs WS-Federation Passive Protocol processing. 
    /// </summary>
    protected void Page_PreRender( object sender, EventArgs e )
    {
        string action = Request.QueryString[WSFederationConstants.Parameters.Action];
 
        try
        {
            if ( action == WSFederationConstants.Actions.SignIn )
            {
                // Process signin request.
                SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri( Request.Url );
                if ( User != null && User.Identity != null && User.Identity.IsAuthenticated )
                {
                    SecurityTokenService sts = 
                        new CustomSecurityTokenService( CustomSecurityTokenServiceConfiguration.Current );
                    SignInResponseMessage responseMessage = 
                        FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest( 
                            requestMessage, 
                            User, 
                            sts );
                    FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse( 
                        responseMessage, Response );
                }
                else
                {
                    throw new UnauthorizedAccessException();
                }
            }
            else if ( action == WSFederationConstants.Actions.SignOut )
            {
                // Process signout request.
                SignOutRequestMessage requestMessage = 
                    (SignOutRequestMessage)WSFederationMessage.CreateFromUri( Request.Url );
                FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest( 
                    requestMessage, 
                    User,
                    requestMessage.Reply, 
                    Response );
            }            
        }
        catch ( ThreadAbortException ) { }
        catch ( Exception exception )
        {
            throw new Exception( "An unexpected error occurred when processing the request. See inner exception for details.", exception );
        }
    }
}

Note two sections here, the first one handles signin requests and it processes these request with respect to our custom security token handler. The second one handles sign out requests, in this case a single request from a single RP application but it’s fairly easy to enhance the code to handle the signout of the whole environment.

This completes the Custom STS. In the next blog entry we will create an RP application federated with our STS.

Wednesday, August 24, 2011

ADFS 2.0 – The quest for customizing ADFS sign-in web pages

Background

The passive WS-Federation protocol becomes an important part of the architecture of our applications. A standalone ADFS works like a charm, also it’s fairly easy to write a custom STS so that the RP application does not not see any difference in the communication protocol (and can be switched between ADFS and a custom STS).

One of the drawbacks of ADFS is that it’s tightly bound to the Active Directory. You can login using username/password and both attributes always come from AD. There’s no way to add your custom authentication logic like “login using email/password” or “login using credentials from the database”. Windows account or nothing. Although you could expect something like “ADFSMembershipProvider” (like the one we have in ASP.NET), there’s none.

To ADFS or not to ADFS

Should one then chose ADFS or rather another STS in a production environment? Good question. Take a look at StarterSTS, it’s what ADFS should be. It supports variety of authentication sources, including custom MembershipProviders. What’s the reason then to stick with ADFS?

To me, the only but damn important reason is that ADFS is an official and mature tool, blessed by Microsoft. There is a difference between “we use the ADFS 2.0” and “we use a custom authentication tool”, no matter how closely such custom tool mimic the way ADFS works and who wrote it.

Towards ADFS customization

Suppose then that, like us, you’ve decided to stay with ADFS. And still, you need a way to customize the authentication logic. The ultimate goal would then be:

The ADFS should be able to pick up an arbitrary logic of authentication (=I want to have something like MembershipProviders for ADFS!)

One of the primary sources which suggest that this is possible is this blog entry by the Identity and Access Team. The entry shows a way to modify the code of the ADFS login page so that it picks up a custom authentication logic, involving a custom STS implementing a WSTrustFeb2005 endpoint.

So what’s the big deal then if someone has already described the solution? Well, take a look at this blog entry and try to follow it.

Have you failed? Well, welcome to the real life.

In fact, the note is rather concise but a lot of work must be done to actually follow it. And it could fail at many, many different levels and stages.

The roadmap

The roadmap is as follows:

  1. Passive federation of ADFS with C-STS (your custom STS)
    1. Implement passive STS functionality in C-STS
    2. Configure the federation between ADFS and C-STS
    3. Test the federation
  2. Active federation of ADFS with C-STS
    1. Implement your custom token handler
    2. Implement WSTrustFeb2005 service endpoint on C-STS
    3. Modify ADFS login logic to authenticate users in C-STS using the WCF endpoint
    4. Test the federation

There is a motivation behind this - the active federation, described in the Identity Blog entry will not work until you correctly federate the ADFS with your STS for a passive scenario. You have to then move on slowly, step by step, and validate each single step until the goal is reached.

And the last thing in this entry – it took me about 5 days to make it work. I will describe all the steps and possible pitfalls in upcoming entries.

IIS7 and easy configuration of SSL host headers

If you ever tried to configure SSL host headers for your IIS7 sites, you already know that this can be done from the IIS management console only for the very first site. If you try to add the SSL binding for another site, the console will prevent you from doing so.

How people usually solve this problem is they use the appcmd commandline tool to add the SSL binding manually for other sites. First, you map add SSL to the very first of your sites manually and then use a script to map another site:

appcmd set site /site.name:"thesitename" /+bindings.[protocol='https',bindingInformation='*:443:host.header.value.com']

However, there’s actually much simpler way to add the SSL binding. It involves manually editing the IIS configuration file, which is C:\Windows\System32\intersrv\config\applicationHost.config. The IIS uses this file to store its configuration.

Edit this file, find a <site> node which refers to your site, it should look like this:

<site name="thesitename" id="3" serverAutoStart="true">
      <application path="/" applicationPool="thepoolname">
          <virtualDirectory path="/" physicalPath="C:\inetpub\somepath" />
      </application>
      <bindings>
          <binding protocol="http" bindingInformation="*:80:host.header.value.com" />
      </bindings>
</site>

Just modify this to:

<site name="thesitename" id="3" serverAutoStart="true">
      <application path="/" applicationPool="thepoolname">
          <virtualDirectory path="/" physicalPath="C:\inetpub\somepath" />
      </application>
      <bindings>
          <binding protocol="http" bindingInformation="*:80:host.header.value.com" />
          <binding protocol="https" bindingInformation="*:443:host.header.value.com" />
      </bindings>
</site>

You can quickly and easily modify all of your sites this way. Then, restart IIS and you are done.

Tuesday, August 23, 2011

ADFS 2.0 – MSIS7012/MSIS3127 when accepting claims from a custom claims provider

The scenario is as follows. You provide a custom claims provider for ADFS2.0 so that when user logs-in to the application, the ADFS should offer a list of possible authentication providers. When the custom provider is selected, ADFS redirects the browser to it. Then, ADFS should accept incoming claims and pass them through to the relying party application.

There are plenty of useful scenarios when this could be handy and people blog about it, for example take a look at this article. In one of our projects we go this route, trying to provide a custom STS to support ADFS with various login options (username/password, email/password, uniqueid/password, name.surname/password etc).

What people seem to have problems with is the number of different issues which arise when the ADFS is up to accept and transform incoming claims. One of such common issues show as MSIS7012/MSIS3127 in the event log:

Microsoft.IdentityServer.Web.RequestFailedException: MSIS7012: Wystąpił błąd podczas przetwarzania żądania. Aby uzyskać szczegółowe informacje, skontaktuj się z administratorem. ---> System.ServiceModel.FaultException: MSIS3127: Określone żądanie nie powiodło się.
   w Microsoft.IdentityServer.Protocols.WSTrust.WSTrustClientManager.Issue(Message request, WCFResponseData responseData)
   w Microsoft.IdentityServer.Protocols.WSTrust.WSTrustClient.Issue(RequestSecurityToken rst, WCFResponseData responseData)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.SubmitRequest(MSISRequestSecurityToken request)
   --- Koniec śladu stosu wyjątków wewnętrznych ---
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.SubmitRequest(MSISRequestSecurityToken request)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.RequestBearerToken(MSISSignInRequestMessage signInRequest, SecurityTokenElement onBehalfOf, SecurityToken primaryAuthToken, String desiredTokenType, Uri& replyTo)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.RequestBearerToken(MSISSignInRequestMessage signInRequest, SecurityTokenElement onBehalfOf, SecurityToken primaryAuthToken, String desiredTokenType, MSISSession& session)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.BuildSignInResponseCoreWithSerializedToken(String signOnToken, WSFederationMessage incomingMessage)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.BuildSignInResponseForProtocolResponse(FederationPassiveContext federationPassiveContext)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.BuildSignInResponse(SecurityToken securityToken)

System.ServiceModel.FaultException: MSIS3127: Określone żądanie nie powiodło się.
   w Microsoft.IdentityServer.Protocols.WSTrust.WSTrustClientManager.Issue(Message request, WCFResponseData responseData)
   w Microsoft.IdentityServer.Protocols.WSTrust.WSTrustClient.Issue(RequestSecurityToken rst, WCFResponseData responseData)
   w Microsoft.IdentityServer.Web.FederationPassiveAuthentication.SubmitRequest(MSISRequestSecurityToken request)

If you take a look at the accompanying event log entry you will learn that:

A token was received from a claims provider identified by the key somekeyhere, but the token could not be validated because the key does not identify any known claims provider trust. Key: somekeyhere. This request failed. User Action If this key represents the certificate thumbprint of a claims provider trust, verify that it matches the signing certificate of the claims provider trust in the AD FS configuration database.

It took like 3 hours to finally find the problem. And the problem is the mismatch between the issuer name provided in the provider’s metadata and the issuer name provided in the ADFS configuration.

First one of these two names is set programmatically somewhere in the configuration of the claims provider, in the SecurityTokenServiceConfiguration class:

public class CustomSecurityTokenServiceConfiguration : SecurityTokenServiceConfiguration
{
    ...
 
    /// <summary>
    /// CustomSecurityTokenServiceConfiguration constructor.
    /// </summary>
    public CustomSecurityTokenServiceConfiguration()
        : base( "ADFS Stub",
                new X509SigningCredentials( the certificate here )
               )
    {
        this.SecurityTokenService = typeof( CustomSecurityTokenService );
    }
}

Note the “ADFS Stub” here – the name is invisible in an explicit form in the metadata because it’s base64’ed somewhere in the certificate description.

The second one of these two names is visible in the explicit form in the ADFS claims trust configuration:

Note that the value of the “Claims provider identifier” attribute (the lower textbox) matches the name provided as the issuer name in the C# code snippet above. If the two do not match you get the exception in the ADFS log.

Monday, July 18, 2011

WIF and custom UserData in authentication cookies

The UserData is a common and yet handy mechanism of authentication frameworks and it consist in injecting a portion of arbitrary data to the authentication information upon logon so that the data is available later during the session.

For example, FormsAuthenticationModule allows to inject userdata to the Forms cookie by manually creating the FormsAuthenticationTicket:

FormsAuthenticationTicket ticket = 
    new FormsAuthenticationTicket(
        1,
        UserName,
        DateTime.Now, DateTime.Now.AddMinutes( 20 ),
        false, "userdata here" );
string cookieValue = FormsAuthentication.Encrypt( ticket );

The similar mechanism in WIF is more “WS-Federation oriented” – you just create a new claim (one or many) of type ClaimTypes.UserData with arbitrary value. How exactly you create such claim? Well, there are two alternatives.

First, you can inject a custom claims authentication manager into the WIF’s pipeline. The manager fires at the beginning of every request and this is where you can inject “per-request” claims.

public class FederatedClaimsAuthenticationManager : ClaimsAuthenticationManager
{
    public override IClaimsPrincipal Authenticate( 
        string resourceName, 
        IClaimsPrincipal incomingPrincipal )
    {
        // If not authenticated - redirect
        if ( !incomingPrincipal.Identity.IsAuthenticated )
            return incomingPrincipal;
 
        // else - inject local claims
        IClaimsIdentity identity = incomingPrincipal.Identity as IClaimsIdentity;
        if ( identity != null && identity.IsAuthenticated )
        {
            identity.Claims.Add( new Claim( ClaimTypes.UserData, 
               "local per-request userdata", ClaimValueTypes.String, "(local)" ) );
        }
 
        return incomingPrincipal;
    }
}

Remember to register the manager in web.config in WIF’s <claimsAuthenticationManager /> section.

But injecting claims at every request is not a choice if you wish to inject userdata once, when user logs in and then be able to read it back at every request.

This is where the second possibility comes in. It consist in injecting the claim during the SessionSecurityTokenCreated event of the WIF’s SessionAuthenticationModule. Since I prefer the FederatedPassiveSignIn user control than direct fedutil.exe approach, I just provide a handler for the user control:

WSFederationLogin.SessionSecurityTokenCreated +=
     ( s, ev ) =>
     {
         ev.SessionToken
            .ClaimsPrincipal.Identities[0]
            .Claims.Add( 
                new Claim( ClaimTypes.UserData, 
                          "local per-session userdata (injected once)", 
                           ClaimValueTypes.String, "(local)" ) );
     };

In both approaches, the UserData claim is present among all other user claims.