Compartilhar via


UserNameSecurityTokenAuthenticator Classe

Definição

Autentica um token de segurança 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
Herança
UserNameSecurityTokenAuthenticator
Derivado

Exemplos

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

Comentários

Substitua a UserNameSecurityTokenAuthenticator classe para autenticar tokens de segurança com base em um nome de usuário e senha.

O Windows Communication Foundation é fornecido com as seguintes classes que dão suporte para autenticar UserNameSecurityToken tokens de segurança.

Tipo Descrição
CustomUserNameSecurityTokenAuthenticator Permite que um aplicativo forneça um esquema de autenticação personalizado para nomes de usuário e senhas. O esquema de autenticação é fornecido usando uma classe derivada da UserNamePasswordValidator classe .
WindowsUserNameSecurityTokenAuthenticator Autentica o nome de usuário e a senha como uma conta do Windows.

A maioria dos esquemas de autenticação personalizados pode usar a CustomUserNameSecurityTokenAuthenticator classe e implementar uma classe derivada da UserNamePasswordValidator classe . No entanto, se for necessária flexibilidade adicional, você poderá derivar uma classe da UserNameSecurityTokenAuthenticator classe e substituir o ValidateUserNamePasswordCore método .

Construtores

UserNameSecurityTokenAuthenticator()

Inicializa uma nova instância da classe UserNameSecurityTokenAuthenticator.

Métodos

CanValidateToken(SecurityToken)

Obtém um valor que indica se o token de segurança especificado pode ser validado pelo autenticador de token de segurança.

(Herdado de SecurityTokenAuthenticator)
CanValidateTokenCore(SecurityToken)

Obtém um valor que indica se o token de segurança especificado pode ser validado pelo autenticador de token de segurança.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)
ValidateToken(SecurityToken)

Autentica o token de segurança especificado e retorna o conjunto de políticas de autorização do token de segurança.

(Herdado de SecurityTokenAuthenticator)
ValidateTokenCore(SecurityToken)

Autentica o token de segurança especificado e retorna o conjunto de políticas de autorização do token de segurança.

ValidateUserNamePasswordCore(String, String)

Quando substituído em uma classe derivada, autentica o nome de usuário e a senha especificados e retorna o conjunto de políticas de autorização para tokens de segurança UserNameSecurityToken.

Aplica-se a