Export (0) Print
Expand All

How to: Create a Custom Security Token Authenticator

This topic shows how to create a custom security token authenticator and how to integrate it with a custom security token manager. A security token authenticator validates the content of a security token provided with an incoming message. If the validation succeeds, the authenticator returns a collection of IAuthorizationPolicy instances that, when evaluated, returns a set of claims.

To use a custom security token authenticator in Windows Communication Foundation (WCF), you must first create custom credentials and security token manager implementations. For more information about creating custom credentials and a security token manager, see Walkthrough: Creating Custom Client and Service Credentials. For more information about credentials, security token manager, and provider and authenticator classes, see Security Architecture.

To create a custom security token authenticator

  1. Define a new class derived from the SecurityTokenAuthenticator class.

  2. Override the CanValidateTokenCore method. The method returns true or false depending on whether the custom authenticator can validate the incoming token type or not.

  3. Override the ValidateTokenCore method. This method needs to validate the token contents appropriately. If the token passes the validation step, it returns a collection of IAuthorizationPolicy instances. The following example uses a custom authorization policy implementation that will be created in the next procedure.

    
    internal class MySecurityTokenAuthenticator : SecurityTokenAuthenticator
    {
        protected override bool CanValidateTokenCore(SecurityToken token)
        {
            // Check that the incoming token is a username token type that  
            // can be validated by this implementation.
            return (token is UserNameSecurityToken);
        }
    
        protected override ReadOnlyCollection<IAuthorizationPolicy> 
            ValidateTokenCore(SecurityToken token)
        {
            UserNameSecurityToken userNameToken = token as UserNameSecurityToken;
    
            // Validate the information contained in the username token. For demonstration 
            // purposes, this code just checks that the user name matches the password.
            if (userNameToken.UserName != userNameToken.Password)
            {
                throw new SecurityTokenValidationException("Invalid user name or password");
            }
    
            // Create just one Claim instance for the username token - the name of the user.
            DefaultClaimSet userNameClaimSet = new DefaultClaimSet(
                ClaimSet.System, 
                new Claim(ClaimTypes.Name, userNameToken.UserName, Rights.PossessProperty));
            List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1);
            policies.Add(new MyAuthorizationPolicy(userNameClaimSet));
            return policies.AsReadOnly();
        }
    }
    
    
    

The previous code returns a collection of authorization policies in the CanValidateToken(SecurityToken) method. WCF does not provide a public implementation of this interface. The following procedure shows how to do so for your own requirements.

To create a custom authorization policy

  1. Define a new class implementing the IAuthorizationPolicy interface.

  2. Implement the Id read-only property. One way to implement this property is to generate a globally unique identifier (GUID) in the class constructor and return it every time the value for this property is requested.

  3. Implement the Issuer read-only property. This property needs to return an issuer of the claim sets that are obtained from the token. This issuer should correspond to the issuer of the token or an authority that is responsible for validating the token contents. The following example uses the issuer claim that passed to this class from the custom security token authenticator created in the previous procedure. The custom security token authenticator uses the system-provided claim set (returned by the System property) to represent the issuer of the username token.

  4. Implement the Evaluate method. This method populates an instance of the EvaluationContext class (passed in as an argument) with claims that are based on the incoming security token content. The method returns true when it is done with the evaluation. In cases when the implementation relies on the presence of other authorization policies that provide additional information to the evaluation context, this method can return false if the required information is not present yet in the evaluation context. In that case, WCF will call the method again after evaluating all other authorization policies generated for the incoming message if at least one of those authorization policies modified the evaluation context.

    
    internal class MyServiceCredentialsSecurityTokenManager : 
        ServiceCredentialsSecurityTokenManager
    {
        ServiceCredentials credentials;
        public MyServiceCredentialsSecurityTokenManager(ServiceCredentials credentials)
            : base(credentials)
        {
            this.credentials = credentials;
        }
    
        public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator
            (SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
        {
            // Return your implementation of the SecurityTokenProvider based on the 
            // tokenRequirement argument.
            SecurityTokenAuthenticator result;
            if (tokenRequirement.TokenType == SecurityTokenTypes.UserName)
            {
                MessageDirection direction = tokenRequirement.GetProperty<MessageDirection>
                    (ServiceModelSecurityTokenRequirement.MessageDirectionProperty);
                if (direction == MessageDirection.Input)
                {
                    outOfBandTokenResolver = null;
                    result = new MySecurityTokenAuthenticator();
                }
                else
                {
                    result = base.CreateSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver);
                }
            }
            else
            {
                result = base.CreateSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver);
            }
    
            return result;
        }
    }
    
    
    

Walkthrough: Creating Custom Client and Service Credentials describes how to create custom credentials and a custom security token manager. To use the custom security token authenticator created here, an implementation of the security token manager is modified to return the custom authenticator from the CreateSecurityTokenAuthenticator method. The method returns an authenticator when an appropriate security token requirement is passed in.

To integrate a custom security token authenticator with a custom security token manager

  1. Override the CreateSecurityTokenAuthenticator method in your custom security token manager implementation.

  2. Add logic to the method to enable it to return your custom security token authenticator based on the SecurityTokenRequirement parameter. The following example returns a custom security token authenticator if the token requirements token type is a user name (represented by the UserName property) and the message direction for which the security token authenticator is being requested is input (represented by the Input field).

    
    internal class MyAuthorizationPolicy : IAuthorizationPolicy
    {
        string id;
        ClaimSet tokenClaims;
        ClaimSet issuer;
    
        public MyAuthorizationPolicy(ClaimSet tokenClaims)
        {
            if (tokenClaims == null)
            {
                throw new ArgumentNullException("tokenClaims");
            }
            this.issuer = tokenClaims.Issuer;
            this.tokenClaims = tokenClaims;
            this.id = Guid.NewGuid().ToString();
        }
    
        public ClaimSet Issuer
        {
            get { return issuer; }
        }
    
        public string Id
        {
            get { return id; }
        }
    
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            // Add the token claim set to the evaluation context.
            evaluationContext.AddClaimSet(this, tokenClaims);
    
            // Return true if the policy evaluation is finished.
            return true;
        }
    }
    
    
    
Show:
© 2014 Microsoft