共用方式為


UserNameSecurityTokenAuthenticator 類別

定義

驗證 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
繼承
UserNameSecurityTokenAuthenticator
衍生

範例

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

備註

覆寫 UserNameSecurityTokenAuthenticator 類別,以便根據使用者名稱和密碼驗證安全性權杖。

Windows Communication Foundation 隨附下列類別,可提供驗證 UserNameSecurityToken 安全性令牌的支援。

類型 描述
CustomUserNameSecurityTokenAuthenticator 允許應用程式提供使用者名稱及密碼的自訂驗證配置。 您可以使用衍生自 UserNamePasswordValidator 類別的類別來提供驗證配置。
WindowsUserNameSecurityTokenAuthenticator 將使用者名稱和密碼當做 Windows 帳號進行驗證。

大部分的自訂驗證配置都可以使用 CustomUserNameSecurityTokenAuthenticator 類別,並實作衍生自 UserNamePasswordValidator 類別的類別。 不過,如果還需要更多的彈性,您可以從 UserNameSecurityTokenAuthenticator 類別衍生類別,並覆寫 ValidateUserNamePasswordCore 方法。

建構函式

UserNameSecurityTokenAuthenticator()

初始化 UserNameSecurityTokenAuthenticator 類別的新執行個體。

方法

CanValidateToken(SecurityToken)

取得值,這個值會指出指定的安全性權杖是否可由這個安全性權杖驗證程式驗證。

(繼承來源 SecurityTokenAuthenticator)
CanValidateTokenCore(SecurityToken)

取得值,這個值會指出指定的安全性權杖是否可由這個安全性權杖驗證程式驗證。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
ValidateToken(SecurityToken)

驗證指定的安全性權杖,並傳回安全性權杖的授權原則集合。

(繼承來源 SecurityTokenAuthenticator)
ValidateTokenCore(SecurityToken)

驗證指定的安全性權杖,並傳回安全性權杖的授權原則集合。

ValidateUserNamePasswordCore(String, String)

在衍生類別中覆寫時,驗證指定的使用者名稱和密碼,並傳回 UserNameSecurityToken 安全性權杖的授權原則集合。

適用於