Como: Examinar o contexto de segurança

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

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

Você também pode determinar quais reivindicações estão sendo feitas em nome do cliente iterando através da coleta de reivindicações na AuthorizationContext propriedade.

Para obter o contexto de segurança atual

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

Para determinar a identidade do chamador

  1. Imprima o valor das PrimaryIdentity propriedades e WindowsIdentity .

Para analisar as reivindicações de um chamador

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

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

Exemplo

O exemplo a seguir imprime os valores e PrimaryIdentity as propriedades do WindowsIdentity contexto de segurança atual e da ClaimType propriedade, o valor do recurso da declaração e a Right propriedade 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:

Consulte também