UserNameSecurityTokenAuthenticator Class

Definition

Authenticates a UserNameSecurityToken security token.

public ref class UserNameSecurityTokenAuthenticator abstract : System::IdentityModel::Selectors::SecurityTokenAuthenticator
public abstract class UserNameSecurityTokenAuthenticator : System.IdentityModel.Selectors.SecurityTokenAuthenticator
type UserNameSecurityTokenAuthenticator = class
    inherit SecurityTokenAuthenticator
Public MustInherit Class UserNameSecurityTokenAuthenticator
Inherits SecurityTokenAuthenticator
Inheritance
UserNameSecurityTokenAuthenticator
Derived

Examples

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Security.Principal;
using System.ServiceModel.Security;
using System.Text.RegularExpressions;

namespace Microsoft.ServiceModel.Samples
{
    class MyTokenAuthenticator : UserNameSecurityTokenAuthenticator
    {
        static bool IsRogueDomain(string domain)
        {
            return false;
        }
        static bool IsEmail(string inputEmail)
        {

            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
            Regex re = new Regex(strRegex);
            if (re.IsMatch(inputEmail))
                return (true);
            else
                return (false);
        }

        bool ValidateUserNameFormat(string UserName)
        {
            if (!IsEmail(UserName))
            {
                Console.WriteLine("Not a valid email");
                return false;
            }
            string[] emailAddress = UserName.Split('@');
            string user = emailAddress[0];
            string domain = emailAddress[1];
            if (IsRogueDomain(domain))
                return false;
            return true;
        }
        protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateUserNamePasswordCore(string userName, string password)
        {
            if (!ValidateUserNameFormat(userName))
                throw new SecurityTokenValidationException("Incorrect UserName format");

            ClaimSet claimSet = new DefaultClaimSet(ClaimSet.System, new Claim(ClaimTypes.Name, userName, Rights.PossessProperty));
            List<IIdentity> identities = new List<IIdentity>(1);
            identities.Add(new GenericIdentity(userName));
            List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1);
            policies.Add(new UnconditionalPolicy(ClaimSet.System, claimSet, DateTime.MaxValue.ToUniversalTime(), identities));
            return policies.AsReadOnly();
        }
    }

    class UnconditionalPolicy : IAuthorizationPolicy
    {
        string id = Guid.NewGuid().ToString();
        ClaimSet issuer;
        ClaimSet issuance;
        DateTime expirationTime;
        IList<IIdentity> identities;

        public UnconditionalPolicy(ClaimSet issuer, ClaimSet issuance, DateTime expirationTime, IList<IIdentity> identities)
        {
            if (issuer == null)
                throw new ArgumentNullException("issuer");
            if (issuance == null)
                throw new ArgumentNullException("issuance");

            this.issuer = issuer;
            this.issuance = issuance;
            this.identities = identities;
            this.expirationTime = expirationTime;
        }

        public string Id
        {
            get { return this.id; }
        }

        public ClaimSet Issuer
        {
            get { return this.issuer; }
        }

        public DateTime ExpirationTime
        {
            get { return this.expirationTime; }
        }

        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            evaluationContext.AddClaimSet(this, this.issuance);

            if (this.identities != null)
            {
                object value;
                IList<IIdentity> contextIdentities;
                if (!evaluationContext.Properties.TryGetValue("Identities", out value))
                {
                    contextIdentities = new List<IIdentity>(this.identities.Count);
                    evaluationContext.Properties.Add("Identities", contextIdentities);
                }
                else
                {
                    contextIdentities = value as IList<IIdentity>;
                }
                foreach (IIdentity identity in this.identities)
                {
                    contextIdentities.Add(identity);
                }
            }

            evaluationContext.RecordExpirationTime(this.expirationTime);
            return true;
        }
    }
}
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Text
Imports System.IdentityModel.Claims
Imports System.IdentityModel.Policy
Imports System.IdentityModel.Selectors
Imports System.IdentityModel.Tokens
Imports System.Security.Principal
Imports System.ServiceModel.Security
Imports System.Text.RegularExpressions



Class MyTokenAuthenticator
    Inherits UserNameSecurityTokenAuthenticator

    Shared Function IsRogueDomain(ByVal domain As String) As Boolean
        Return False

    End Function 'IsRogueDomain

    Shared Function IsEmail(ByVal inputEmail As String) As Boolean

        Dim strRegex As String = "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
        Dim re As New Regex(strRegex)
        If re.IsMatch(inputEmail) Then
            Return True
        Else
            Return False
        End If

    End Function 'IsEmail

    Function ValidateUserNameFormat(ByVal UserName As String) As Boolean
        If Not IsEmail(UserName) Then
            Console.WriteLine("Not a valid email")
            Return False
        End If
        Dim emailAddress As String() = UserName.Split("@"c)
        Dim user As String = emailAddress(0)
        Dim domain As String = emailAddress(1)
        If IsRogueDomain(domain) Then
            Return False
        End If
        Return True

    End Function

    Protected Overrides Function ValidateUserNamePasswordCore(ByVal userName As String, ByVal password As String) As ReadOnlyCollection(Of IAuthorizationPolicy)

        If Not ValidateUserNameFormat(userName) Then
            Throw New SecurityTokenValidationException("Incorrect UserName format")
        End If
        Dim setOfClaims As New DefaultClaimSet(ClaimSet.System, New Claim(ClaimTypes.Name, userName, Rights.PossessProperty))
        Dim identities As New List(Of IIdentity)(1)

        identities.Add(New GenericIdentity(userName))
        Dim policies As New List(Of IAuthorizationPolicy)(1)
        policies.Add(New UnconditionalPolicy(ClaimSet.System, setOfClaims, DateTime.MaxValue.ToUniversalTime(), identities))
        Return policies.AsReadOnly()

    End Function 'New
End Class


Class UnconditionalPolicy
    Implements IAuthorizationPolicy
    Private idValue As String = Guid.NewGuid().ToString()
    Private issuerValue As ClaimSet
    Private issuance As ClaimSet
    Private expirationTimeValue As DateTime
    Private identities As IList(Of IIdentity)
    Public Sub New(ByVal issuer As ClaimSet, ByVal issuance As ClaimSet, ByVal expirationTime As DateTime, ByVal identities As IList(Of IIdentity))

        If issuer Is Nothing Then
            Throw New ArgumentNullException("issuer")
        End If
        If issuance Is Nothing Then
            Throw New ArgumentNullException("issuance")
        End If
        Me.issuerValue = issuer
        Me.issuance = issuance
        Me.identities = identities
        Me.expirationTimeValue = expirationTime
    End Sub
    Public ReadOnly Property Id() As String Implements IAuthorizationPolicy.Id
        Get
            Return Me.idValue
        End Get
    End Property
    Public ReadOnly Property Issuer() As ClaimSet Implements IAuthorizationPolicy.Issuer
        Get
            Return Me.issuerValue
        End Get
    End Property
    Public ReadOnly Property ExpirationTime() As DateTime
        Get
            Return Me.expirationTimeValue
        End Get
    End Property
    Public Function Evaluate(ByVal evalContext As evaluationContext, ByRef state As Object) As Boolean Implements IAuthorizationPolicy.Evaluate
        evalContext.AddClaimSet(Me, Me.issuance)

        If Not (Me.identities Is Nothing) Then
            Dim value As Object = Nothing
            Dim contextIdentities As IList(Of IIdentity)
            If Not evalContext.Properties.TryGetValue("Identities", value) Then
                contextIdentities = New List(Of IIdentity)(Me.identities.Count) '
                evalContext.Properties.Add("Identities", contextIdentities)
            Else
                contextIdentities = CType(value, IList(Of IIdentity))
            End If
            Dim identity As IIdentity
            For Each identity In Me.identities
                contextIdentities.Add(identity)
            Next identity
        End If

        evalContext.RecordExpirationTime(Me.expirationTimeValue)
        Return True

    End Function
End Class

Remarks

Override the UserNameSecurityTokenAuthenticator class to authenticate security tokens based on a user name and password.

Windows Communication Foundation ships with the following classes that provide support for authenticating UserNameSecurityToken security tokens.

Type Description
CustomUserNameSecurityTokenAuthenticator Allows an application to provide a custom authentication scheme for user names and passwords. The authentication scheme is provided using a class deriving from the UserNamePasswordValidator class.
WindowsUserNameSecurityTokenAuthenticator Authenticates the user name and password as a Windows account.

Most custom authentication schemes can use the use the CustomUserNameSecurityTokenAuthenticator class and implement a class that derives from the UserNamePasswordValidator class. However, if additional flexibility is needed, you can derive a class from the UserNameSecurityTokenAuthenticator class and override the ValidateUserNamePasswordCore method.

Constructors

UserNameSecurityTokenAuthenticator()

Initializes a new instance of the UserNameSecurityTokenAuthenticator class.

Methods

CanValidateToken(SecurityToken)

Gets a value indicating whether the specified security token can be validated by this security token authenticator.

(Inherited from SecurityTokenAuthenticator)
CanValidateTokenCore(SecurityToken)

Gets a value indicating whether the specified security token can be validated by this security token authenticator.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Returns a string that represents the current object.

(Inherited from Object)
ValidateToken(SecurityToken)

Authenticates the specified security token and returns the set of authorization policies for the security token.

(Inherited from SecurityTokenAuthenticator)
ValidateTokenCore(SecurityToken)

Authenticates the specified security token and returns the set of authorization policies for the security token.

ValidateUserNamePasswordCore(String, String)

When overridden in a derived class, authenticates the specified user name and password and returns the set of authorization policies for UserNameSecurityToken security tokens.

Applies to