ServiceSecurityContext Класс

Определение

Представляет контекст безопасности удаленной стороны. На клиенте представляет удостоверение службы, а в службе — удостоверение клиента.

public ref class ServiceSecurityContext
public class ServiceSecurityContext
type ServiceSecurityContext = class
Public Class ServiceSecurityContext
Наследование
ServiceSecurityContext

Примеры

В следующем примере класс используется ServiceSecurityContext для предоставления сведений о текущем контексте безопасности. Код создает экземпляр StreamWriter класса для записи сведений в файл.

// When this method runs, the caller must be an authenticated user
// and the ServiceSecurityContext is not a null instance.
public double Add(double n1, double n2)
{
    // Write data from the ServiceSecurityContext to a file using the StreamWriter class.
    using (StreamWriter sw = new StreamWriter(@"c:\ServiceSecurityContextInfo.txt"))
    {
        // Write the primary identity and Windows identity. The primary identity is derived from
        // the credentials used to authenticate the user. The Windows identity may be a null string.
        sw.WriteLine("PrimaryIdentity: {0}", ServiceSecurityContext.Current.PrimaryIdentity.Name);
        sw.WriteLine("WindowsIdentity: {0}", ServiceSecurityContext.Current.WindowsIdentity.Name);

        // Write the claimsets in the authorization context. By default, there is only one claimset
        // provided by the system.
        foreach (ClaimSet claimset in ServiceSecurityContext.Current.AuthorizationContext.ClaimSets)
        {
            foreach (Claim claim in claimset)
            {
                // Write out each claim type, claim value, and the right. There are two
                // possible values for the right: "identity" and "possessproperty".
                sw.WriteLine("Claim Type: {0}, Resource: {1} Right: {2}",
                    claim.ClaimType,
                    claim.Resource.ToString(),
                    claim.Right);
                sw.WriteLine();
            }
        }
    }
    return n1 + n2;
}
' When this method runs, the caller must be an authenticated user and the ServiceSecurityContext 
' is not a null instance. 
Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
    ' Write data from the ServiceSecurityContext to a file using the StreamWriter class.
    Dim sw As New StreamWriter("c:\ServiceSecurityContextInfo.txt")
    Try
        ' Write the primary identity and Windows identity. The primary identity is derived from 
        ' the credentials used to authenticate the user. The Windows identity may be a null string.
        sw.WriteLine("PrimaryIdentity: {0}", ServiceSecurityContext.Current.PrimaryIdentity.Name)
        sw.WriteLine("WindowsIdentity: {0}", ServiceSecurityContext.Current.WindowsIdentity.Name)

        ' Write the claimsets in the authorization context. By default, there is only one claimset
        ' provided by the system. 
        Dim claimset As ClaimSet
        For Each claimset In ServiceSecurityContext.Current.AuthorizationContext.ClaimSets
            Dim claim As Claim
            For Each claim In claimset
                ' Write out each claim type, claim value, and the right. There are two
                ' possible values for the right: "identity" and "possessproperty". 
                sw.WriteLine("Claim Type: {0}, Resource: {1} Right: {2}", _
                claim.ClaimType, _
                claim.Resource.ToString(), _
                claim.Right)
                sw.WriteLine()
            Next claim
        Next claimset
    Finally
        sw.Dispose()
    End Try
    Return n1 + n2
End Function

В следующем примере показана реализация CheckAccessCore метода, который использует ServiceSecurityContext для синтаксического анализа набора утверждений.

public class MyServiceAuthorizationManager : ServiceAuthorizationManager
{
    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        // Extract the action URI from the OperationContext. Match this against the claims
        // in the AuthorizationContext.
        string action = operationContext.RequestContext.RequestMessage.Headers.Action;
        Console.WriteLine("action: {0}", action);

        // Iterate through the various claimsets in the AuthorizationContext.
        foreach(ClaimSet cs in operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets)
        {
            // Examine only those claim sets issued by System.
            if (cs.Issuer == ClaimSet.System)
            {
                // Iterate through claims of type "http://example.org/claims/allowedoperation".
                foreach (Claim c in cs.FindClaims("http://example.org/claims/allowedoperation",
                    Rights.PossessProperty))
                {
                    // Write the Claim resource to the console.
                    Console.WriteLine("resource: {0}", c.Resource.ToString());

                    // If the Claim resource matches the action URI then return true to allow access.
                    if (action == c.Resource.ToString())
                        return true;
                }
            }
        }

        // If this point is reached, return false to deny access.
         return false;
    }
}
Public Class MyServiceAuthorizationManager
    Inherits ServiceAuthorizationManager
    
    Protected Overrides Function CheckAccessCore(ByVal operationContext As OperationContext) As Boolean 
        ' Extract the action URI from the OperationContext. Match this against the claims
        ' in the AuthorizationContext.
        Dim action As String = operationContext.RequestContext.RequestMessage.Headers.Action
        Console.WriteLine("action: {0}", action)
        
        ' Iterate through the various claimsets in the authorizationcontext.
        Dim cs As ClaimSet
        For Each cs In  operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets
            ' Examine only those claim sets issued by System.
            If cs.Issuer Is ClaimSet.System Then
                ' Iterate through claims of type "http://example.org/claims/allowedoperation".
                Dim c As Claim
                For Each c In  cs.FindClaims("http://example.org/claims/allowedoperation", _
                        Rights.PossessProperty)
                    ' Write the Claim resource to the console.
                    Console.WriteLine("resource: {0}", c.Resource.ToString())
                    
                    ' If the Claim resource matches the action URI then return true to allow access.
                    If action = c.Resource.ToString() Then
                        Return True
                    End If
                Next c
            End If
        Next cs 
        ' If we get here, return false, denying access.
        Return False
    
    End Function 
End Class

Комментарии

Данные являются частью SecurityMessageProperty сообщения.

Используйте этот класс для получения сведений о контексте удаленной безопасности во время выполнения. Контекст безопасности создается, когда клиент успешно проходит проверку подлинности и авторизован для доступа к методу. Когда сообщение успешно проходит проверку подлинности и авторизовано, данные безопасности от клиента и текущего экземпляра службы можно получить из экземпляра этого класса.

Можно получить экземпляр ServiceSecurityContext из Current свойства OperationContext класса или использовать его из метода операции службы, как показано в следующем примере.

Анализ набора утверждений

Обычное использование класса заключается в получении текущего набора утверждений для идентификации или авторизации клиента при доступе к методу. Класс ClaimSet содержит коллекцию Claim объектов, и каждый из них можно проанализировать, чтобы определить, присутствует ли конкретное утверждение. Если указано указанное утверждение, авторизация может быть предоставлена. Эта функция предоставляется путем переопределения CheckAccessCore метода ServiceAuthorizationManager класса. Полный пример см. в разделе "Политика авторизации".

Обратите внимание, IsAuthenticated что в некоторых случаях свойство IIdentity интерфейса возвращается true , даже если удаленный клиент проходит проверку подлинности в качестве анонимного пользователя. (Свойство PrimaryIdentity возвращает реализацию IIdentity интерфейса.) Для этого должны быть верны следующие обстоятельства:

  • Служба использует проверку подлинности Windows.

  • Служба разрешает анонимный вход.

  • Привязка <— это customBinding>.

  • Пользовательская привязка включает <security> элемент.

  • Элемент <security> включает <secureConversationBootstrap> с заданным атрибутом requireSecurityContextCancellationfalse.

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

Имя Описание
ServiceSecurityContext(AuthorizationContext, ReadOnlyCollection<IAuthorizationPolicy>)

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

ServiceSecurityContext(AuthorizationContext)

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

ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy>)

Инициализирует новый экземпляр ServiceSecurityContext класса с помощью коллекции объектов политик.

Свойства

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

Возвращает экземпляр ServiceSecurityContext класса, который содержит пустую коллекцию утверждений, удостоверений и других данных контекста, которые обычно используются для представления анонимной стороны.

AuthorizationContext

Возвращает сведения о авторизации для экземпляра этого класса. Содержит AuthorizationContext коллекцию ClaimSet , которую приложение может допросить и получить информацию стороны.

AuthorizationPolicies

Возвращает коллекцию политик, связанных с экземпляром этого класса.

Current

Возвращает текущий ServiceSecurityContext.

IsAnonymous

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

PrimaryIdentity

Возвращает основное удостоверение, связанное с текущим параметром.

WindowsIdentity

Возвращает удостоверение Windows текущего параметра.

Методы

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

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

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

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

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

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

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

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

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

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

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

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

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