Compartir a través de


UserNameSecurityTokenAuthenticator Clase

Definición

Autentica un token de seguridad UserNameSecurityToken.

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
Herencia
UserNameSecurityTokenAuthenticator
Derivado

Ejemplos

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

Comentarios

Invalide la clase UserNameSecurityTokenAuthenticator para autenticar tokens de seguridad basados en un nombre de usuario y contraseña.

Windows Communication Foundation se incluye con las siguientes clases que proporcionan compatibilidad con la autenticación de UserNameSecurityToken tokens de seguridad.

Tipo Descripción
CustomUserNameSecurityTokenAuthenticator Permite proporcionar a una aplicación un esquema de autenticación personalizada para los nombres de usuario y contraseñas. El esquema de autenticación se proporciona utilizando una clase que deriva de la clase UserNamePasswordValidator.
WindowsUserNameSecurityTokenAuthenticator Autentica el nombre de usuario y contraseña como una cuenta de Windows.

La mayoría de los esquemas de autenticación personalizada pueden utilizar el uso la clase CustomUserNameSecurityTokenAuthenticator e implementar una clase que deriva de la clase UserNamePasswordValidator. Sin embargo, si se necesita la flexibilidad adicional, puede derivar una clase de la clase UserNameSecurityTokenAuthenticator e invalidar el método ValidateUserNamePasswordCore.

Constructores

UserNameSecurityTokenAuthenticator()

Inicializa una nueva instancia de la clase UserNameSecurityTokenAuthenticator.

Métodos

CanValidateToken(SecurityToken)

Obtiene un valor que indica si el autenticador de tokens de seguridad puede validar el token de seguridad especificado.

(Heredado de SecurityTokenAuthenticator)
CanValidateTokenCore(SecurityToken)

Obtiene un valor que indica si el autenticador de tokens de seguridad puede validar el token de seguridad especificado.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
ValidateToken(SecurityToken)

Autentica el token de seguridad especificado y devuelve el conjunto de directivas de autorización del token de seguridad.

(Heredado de SecurityTokenAuthenticator)
ValidateTokenCore(SecurityToken)

Autentica el token de seguridad especificado y devuelve el conjunto de directivas de autorización del token de seguridad.

ValidateUserNamePasswordCore(String, String)

Cuando se invalida en una clase derivada, autentica el nombre de usuario especificado y contraseña y devuelve el conjunto de directivas de la autorización para los tokens de seguridad UserNameSecurityToken.

Se aplica a