ServiceSecurityContext Classe

Definição

Representa o contexto de segurança de uma parte remota. No cliente, representa a identidade do serviço e, no serviço, representa a identidade do cliente.

public ref class ServiceSecurityContext
public class ServiceSecurityContext
type ServiceSecurityContext = class
Public Class ServiceSecurityContext
Herança
ServiceSecurityContext

Exemplos

O exemplo a seguir usa a ServiceSecurityContext classe para fornecer informações sobre o contexto de segurança atual. O código cria uma instância da StreamWriter classe para gravar as informações em um arquivo.

// 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

O exemplo a seguir mostra uma implementação do CheckAccessCore método que usa a ServiceSecurityContext análise de um conjunto de declarações.

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

Comentários

Os dados fazem parte de SecurityMessageProperty uma mensagem.

Use essa classe para obter informações sobre um contexto de segurança remota em runtime. Um contexto de segurança é criado quando um cliente é autenticado com êxito e autorizado a acessar um método. Quando uma mensagem é autenticada e autorizada com êxito, as informações de segurança do cliente e da instância de serviço atual podem ser obtidas de uma instância dessa classe.

Você pode recuperar uma instância da ServiceSecurityContext Current propriedade da OperationContext classe ou usá-la de dentro de um método de operação de serviço, conforme mostrado no exemplo a seguir.

Analisando um ClaimSet

Um uso comum da classe é recuperar o conjunto atual de declarações com a finalidade de identificar ou autorizar um cliente ao acessar um método. A ClaimSet classe contém uma coleção de Claim objetos e cada um pode ser analisado para determinar se uma declaração específica está presente. Se a declaração especificada for fornecida, a autorização poderá ser concedida. Essa funcionalidade é fornecida substituindo o CheckAccessCore método da ServiceAuthorizationManager classe. Para obter um exemplo completo, consulte a Política de Autorização.

Observe que, em algumas circunstâncias, a IsAuthenticated propriedade da IIdentity interface retorna true mesmo que o cliente remoto seja autenticado como um usuário anônimo. (A PrimaryIdentity propriedade retorna uma implementação da IIdentity interface.) As seguintes circunstâncias devem ser verdadeiras para que isso ocorra:

  • O serviço usa autenticação do Windows.

  • O serviço permite logons anônimos.

  • A associação é uma <customBinding>.

  • A associação personalizada inclui um <security> elemento.

  • O <security> elemento inclui um <secureConversationBootstrap> com o requireSecurityContextCancellation atributo definido como false.

Construtores

ServiceSecurityContext(AuthorizationContext)

Inicializa uma nova instância da classe ServiceSecurityContext com os parâmetros de autorização especificados.

ServiceSecurityContext(AuthorizationContext, ReadOnlyCollection<IAuthorizationPolicy>)

Inicializa uma nova instância da classe ServiceSecurityContext com a coleção de políticas e os parâmetros de autorização especificados.

ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy>)

Inicializa uma nova instância da classe ServiceSecurityContext com o objeto de coleção de políticas.

Propriedades

Anonymous

Retorna uma instância da classe ServiceSecurityContext que contém uma coleção vazia de declarações, identidades e outros dados de contexto que normalmente são usados para representar uma parte anônima.

AuthorizationContext

Obtém as informações de autorização de uma instância dessa classe. O AuthorizationContext contém uma coleção de ClaimSet que o aplicativo pode interrogar e recuperar as informações da parte.

AuthorizationPolicies

Obtém a coleção de políticas associadas a uma instância dessa classe.

Current

Obtém o ServiceSecurityContext atual.

IsAnonymous

Obtém um valor que indica se o cliente atual forneceu credenciais para o serviço.

PrimaryIdentity

Obtém a identidade primária associada à configuração atual.

WindowsIdentity

Obtém a identidade do Windows da configuração atual.

Métodos

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)

Aplica-se a

Confira também