Share via


Como: examinar o contexto de segurança

Ao programar serviços do WCF (Windows Communication Foundation), o contexto de segurança do serviço permite que você determine detalhes sobre as credenciais do cliente e declarações usadas para autenticar com o serviço. Isso é feito usando as propriedades da classe ServiceSecurityContext.

Por exemplo, você pode recuperar a identidade do cliente atual usando a propriedade PrimaryIdentity ou a propriedade WindowsIdentity. Para determinar se o cliente é anônimo, use a propriedade IsAnonymous.

Você também pode determinar quais declarações estão sendo feitas em nome do cliente iterando por meio da coleção de declarações na propriedade AuthorizationContext.

Para obter o contexto de segurança atual

  • Acesse a propriedade Current estática para obter o contexto de segurança atual. Examine qualquer uma das propriedades do contexto atual da referência.

Para determinar a identidade do autor da chamada

  1. Imprima o valor das propriedades PrimaryIdentity e WindowsIdentity.

Para analisar as declarações de um chamador

  1. Retorne a classe atual AuthorizationContext. Use a propriedade Current para retornar o contexto de segurança do serviço atual e, em seguida, retornar o AuthorizationContext usando a propriedade AuthorizationContext.

  2. Analise a coleção de objetos ClaimSet retornados pela propriedade ClaimSets da classe AuthorizationContext.

Exemplo

O exemplo a seguir imprime os valores e as propriedades WindowsIdentity e PrimaryIdentity do contexto de segurança atual e da propriedade ClaimType, o valor do recurso da declaração e a propriedade Right de cada declaração no contexto de segurança atual.

// Run this method from within a method protected by the PrincipalPermissionAttribute
// to see the security context data, including the primary identity.
public void WriteServiceSecurityContextData(string fileName)
{
    using (StreamWriter sw = new StreamWriter(fileName))
    {
        // 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);
        sw.WriteLine();
        // 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}", claim.ClaimType);
                sw.WriteLine("\t Resource = {0}", claim.Resource.ToString());
                sw.WriteLine("\t Right = {0}", claim.Right);
            }
        }
    }
}

' Run this method from within a method protected by the PrincipalPermissionAttribute
' to see the security context data, including the primary identity.
Public Sub WriteServiceSecurityContextData(ByVal fileName As String)
    Dim sw As New StreamWriter(fileName)
    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)
        sw.WriteLine()
        ' 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}", claim.ClaimType)
                sw.WriteLine(vbTab + " Resource = {0}", claim.Resource.ToString())
                sw.WriteLine(vbTab + " Right = {0}", claim.Right)
            Next claim
        Next claimset
    Finally
        sw.Dispose()
    End Try

End Sub

Compilando o código

O código usa os seguintes namespaces:

Confira também