SecurityTokenProvider Класс

Определение

Представляет поставщик маркеров безопасности, который обрабатывает маркеры безопасности для отправителя сообщения SOAP.

public ref class SecurityTokenProvider abstract
public abstract class SecurityTokenProvider
type SecurityTokenProvider = class
Public MustInherit Class SecurityTokenProvider
Наследование
SecurityTokenProvider
Производный

Примеры

using System;

using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;

using System.IO;

using System.ServiceModel.Security;

using System.Xml;

namespace Microsoft.ServiceModel.Samples
{
    /// <summary>
    /// class that derives from SecurityTokenProvider and returns a SecurityToken representing a SAML assertion
    /// </summary>
    public class SamlSecurityTokenProvider : SecurityTokenProvider
    {
        /// <summary>
        /// The SAML assertion that the SamlSecurityTokenProvider will return as a SecurityToken
        /// </summary>
        SamlAssertion assertion;

        /// <summary>
        /// The proof token associated with the SAML assertion
        /// </summary>
        SecurityToken proofToken;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assertion">The SAML assertion that the SamlSecurityTokenProvider will return as a SecurityToken</param>
        /// <param name="proofToken">The proof token associated with the SAML assertion</param>
        public SamlSecurityTokenProvider(SamlAssertion assertion, SecurityToken proofToken )
        {
            this.assertion = assertion;
            this.proofToken = proofToken;
        }

        /// <summary>
        /// Creates the security token
        /// </summary>
        /// <param name="timeout">Maximum amount of time the method is supposed to take. Ignored in this implementation.</param>
        /// <returns>A SecurityToken corresponding the SAML assertion and proof key specified at construction time</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            // Create a SamlSecurityToken from the provided assertion
            SamlSecurityToken samlToken = new SamlSecurityToken(assertion);

            // Create a SecurityTokenSerializer that will be used to serialize the SamlSecurityToken
            WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer();

            // Create a memory stream to write the serialized token into
            // Use an initial size of 64Kb
            MemoryStream s = new MemoryStream(UInt16.MaxValue);

            // Create an XmlWriter over the stream
            XmlWriter xw = XmlWriter.Create(s);

            // Write the SamlSecurityToken into the stream
            ser.WriteToken(xw, samlToken);

            // Seek back to the beginning of the stream
            s.Seek(0, SeekOrigin.Begin);

            // Load the serialized token into a DOM
            XmlDocument dom = new XmlDocument();
            dom.Load(s);

            // Create a KeyIdentifierClause for the SamlSecurityToken
            SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = samlToken.CreateKeyIdentifierClause<SamlAssertionKeyIdentifierClause>();

            // Return a GenericXmlToken from the XML for the SamlSecurityToken, the proof token, the valid from
            // and valid until times from the assertion and the key identifier clause created above
            return new GenericXmlSecurityToken(dom.DocumentElement, proofToken, assertion.Conditions.NotBefore, assertion.Conditions.NotOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null);
        }
    }
}
Imports System.IdentityModel.Selectors
Imports System.IdentityModel.Tokens

Imports System.IO

Imports System.ServiceModel.Security

Imports System.Xml


'/ <summary>
'/ class that derives from SecurityTokenProvider and returns a SecurityToken representing a SAML assertion
'/ </summary>

Public Class SamlSecurityTokenProvider
    Inherits SecurityTokenProvider
    '/ <summary>
    '/ The SAML assertion that the SamlSecurityTokenProvider will return as a SecurityToken
    '/ </summary>
    Private assertion As SamlAssertion

    '/ <summary>
    '/ The proof token associated with the SAML assertion
    '/ </summary>
    Private proofToken As SecurityToken


    '/ <summary>
    '/ Constructor
    '/ </summary>
    '/ <param name="assertion">The SAML assertion that the SamlSecurityTokenProvider will return as a SecurityToken</param>
    '/ <param name="proofToken">The proof token associated with the SAML assertion</param>
    Public Sub New(ByVal assertion As SamlAssertion, ByVal proofToken As SecurityToken)
        Me.assertion = assertion
        Me.proofToken = proofToken

    End Sub


    '/ <summary>
    '/ Creates the security token
    '/ </summary>
    '/ <param name="timeout">Maximum amount of time the method is supposed to take. Ignored in this implementation.</param>
    '/ <returns>A SecurityToken corresponding the SAML assertion and proof key specified at construction time</returns>
    Protected Overrides Function GetTokenCore(ByVal timeout As TimeSpan) As SecurityToken
        ' Create a SamlSecurityToken from the provided assertion
        Dim samlToken As New SamlSecurityToken(assertion)

        ' Create a SecurityTokenSerializer that will be used to serialize the SamlSecurityToken
        Dim ser As New WSSecurityTokenSerializer()

        ' Create a memory stream to write the serialized token into
        ' Use an initial size of 64Kb
        Dim s As New MemoryStream(UInt16.MaxValue)

        ' Create an XmlWriter over the stream
        Dim xw As XmlWriter = XmlWriter.Create(s)

        ' Write the SamlSecurityToken into the stream
        ser.WriteToken(xw, samlToken)

        ' Seek back to the beginning of the stream
        s.Seek(0, SeekOrigin.Begin)

        ' Load the serialized token into a DOM
        Dim dom As New XmlDocument()
        dom.Load(s)

        ' Create a KeyIdentifierClause for the SamlSecurityToken
        Dim samlKeyIdentifierClause As SamlAssertionKeyIdentifierClause = samlToken.CreateKeyIdentifierClause(Of SamlAssertionKeyIdentifierClause)()
        
        ' Return a GenericXmlToken from the XML for the SamlSecurityToken, the proof token, the valid from 
        ' and valid until times from the assertion and the key identifier clause created above            
        Return New GenericXmlSecurityToken(dom.DocumentElement, proofToken, assertion.Conditions.NotBefore, assertion.Conditions.NotOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, Nothing)

    End Function 'GetTokenCore
End Class

Комментарии

Используйте класс, SecurityTokenProvider когда требуются пользовательские маркеры безопасности. Роль поставщика маркеров безопасности заключается в получении маркера безопасности при отправке клиентом сообщения SOAP, а маркер безопасности используется для проверки подлинности клиента или защиты сообщения SOAP. В частности, GetToken метод вызывается для получения маркера безопасности. Поставщик маркеров безопасности также можно вызвать для отмены и продления безопасности с помощью CancelToken методов и RenewToken методов.

Классы, производные SecurityTokenManager от класса, реализуют CreateSecurityTokenProvider метод, чтобы определить, какой поставщик маркеров безопасности требуется для данного маркера безопасности.

ClientCredentialsSecurityTokenManager Классы ServiceCredentialsSecurityTokenManager предоставляют реализации по умолчанию для встроенных типов маркеров безопасности. Для сценариев пользовательского маркера безопасности необходимо наследить класс от одного из SecurityTokenManagerClientCredentialsSecurityTokenManagerклассов или ServiceCredentialsSecurityTokenManager классов и предоставить функциональные возможности для создания поставщика маркеров безопасности, средства проверки подлинности маркеров безопасности и сериализатора маркеров безопасности для пользовательского маркера безопасности. Дополнительные сведения о создании пользовательского токена см. в статье "Практическое руководство. Создание пользовательского маркера".

Конструкторы

Имя Описание
SecurityTokenProvider()

Инициализирует новый экземпляр класса SecurityTokenProvider.

Свойства

Имя Описание
SupportsTokenCancellation

Возвращает значение, указывающее, можно ли отменить маркер безопасности.

SupportsTokenRenewal

Возвращает значение, указывающее, является ли маркер безопасности возобновляемым.

Методы

Имя Описание
BeginCancelToken(TimeSpan, SecurityToken, AsyncCallback, Object)

Начинает асинхронную операцию отмены маркера безопасности.

BeginCancelTokenCore(TimeSpan, SecurityToken, AsyncCallback, Object)

Начинает асинхронную операцию отмены маркера безопасности.

BeginGetToken(TimeSpan, AsyncCallback, Object)

Начинает асинхронную операцию для получения маркера безопасности.

BeginGetTokenCore(TimeSpan, AsyncCallback, Object)

Начинает асинхронную операцию для получения маркера безопасности.

BeginRenewToken(TimeSpan, SecurityToken, AsyncCallback, Object)

Начинает асинхронную операцию, которая обновляет маркер безопасности.

BeginRenewTokenCore(TimeSpan, SecurityToken, AsyncCallback, Object)

Начинает асинхронную операцию, которая обновляет маркер безопасности.

CancelToken(TimeSpan, SecurityToken)

Отменяет маркер безопасности.

CancelTokenAsync(TimeSpan, SecurityToken)

Отменяет маркер безопасности.

CancelTokenCore(TimeSpan, SecurityToken)

Отменяет маркер безопасности.

CancelTokenCoreAsync(TimeSpan, SecurityToken)

Отменяет маркер безопасности.

EndCancelToken(IAsyncResult)

Завершает асинхронную операцию для отмены маркера безопасности.

EndCancelTokenCore(IAsyncResult)

Завершает асинхронную операцию для отмены маркера безопасности.

EndGetToken(IAsyncResult)

Завершает асинхронную операцию, чтобы получить маркер безопасности.

EndGetTokenCore(IAsyncResult)

Завершает асинхронную операцию, чтобы получить маркер безопасности.

EndRenewToken(IAsyncResult)

Завершает асинхронную операцию для продления маркера безопасности.

EndRenewTokenCore(IAsyncResult)

Завершает асинхронную операцию для продления маркера безопасности.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetToken(TimeSpan)

Возвращает маркер безопасности.

GetTokenAsync(TimeSpan)

Возвращает маркер безопасности.

GetTokenCore(TimeSpan)

Возвращает маркер безопасности.

GetTokenCoreAsync(TimeSpan)

Возвращает маркер безопасности.

GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
RenewToken(TimeSpan, SecurityToken)

Обновляет маркер безопасности.

RenewTokenAsync(TimeSpan, SecurityToken)

Обновляет маркер безопасности.

RenewTokenCore(TimeSpan, SecurityToken)

Обновляет маркер безопасности.

RenewTokenCoreAsync(TimeSpan, SecurityToken)

Обновляет маркер безопасности.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к

См. также раздел