Compartilhar via


Acessando diretamente um objeto de entidade

Embora o uso de demandas imperativas e declarativas para invocar as verificações de segurança baseada em função é o principal mecanismo de verificação e aplicação de participação de identidade e função, pode haver casos em que você deseja acessar a Principal objeto e seu associado identidade o objeto diretamente para fazer tarefas de autorização sem criar objetos de permissão. Por exemplo, não convém usar demandas declarativas ou imperativas se não quiser que uma exceção gerada para ser o comportamento padrão para a falha de validação. Nesse caso, você pode usar estática CurrentPrincipal propriedade no System.Threading.Thread a classe de acesso a Principal object e chamar seus métodos.

Depois de obter o objeto principal, você pode usar instruções condicionais para controlar o acesso ao código com base no nome principal, como mostrado no exemplo de código a seguir.

WindowsPrincipal MyPrincipal = 
    (WindowsPrincipal)Thread.CurrentPrincipal;
if (MyPrincipal.Identity.Name == "fred") 
    // Permit access to some code. 
Dim MyPrincipal As WindowsPrincipal = _
    CType(Thread.CurrentPrincipal, WindowsPrincipal)
If (MyPrincipal.Identity.Name = "fred") Then
    ' Permit access to some code.
End If

Você também programaticamente pode verificar a participação em funções chamando o IsInRole método no atual Principal objeto conforme mostrado no exemplo de código a seguir.

// Get the current identity.
WindowsIdentity MyIdent = WindowsIdentity.GetCurrent();

// Create a principal.
WindowsPrincipal MyPrincipal = new WindowsPrincipal(MyIdent);

// Check the role using a string.
if (MyPrincipal.IsInRole(@"BUILTIN\Administrators"))
{
    Console.WriteLine("You are an administrator.");
}
else
{
    Console.WriteLine("You are not an administrator.");
}
// Check the role using an enumeration.
if (MyPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
    Console.WriteLine("You are an administrator.");
}
else
{
    Console.WriteLine("You are not an administrator.");
}
' Get the current identity.
Dim MyIdent As WindowsIdentity = WindowsIdentity.GetCurrent()

' Create a principal.
Dim MyPrincipal As New WindowsPrincipal(MyIdent)

' Check the role using a string.
If MyPrincipal.IsInRole("BUILTIN\Administrators") Then
    Console.WriteLine("You are an administrator.")
Else
    Console.WriteLine("You are not an administrator.")
End If
' Check the role using an enumeration.
If MyPrincipal.IsInRole(WindowsBuiltInRole.Administrator) Then
    Console.WriteLine("You are an administrator.")
Else
    Console.WriteLine("You are not an administrator.")
End If

Você pode usar essa técnica, quando você deseja acessar os comportamentos são específicos de uma definição de aplicativo Principal objeto. No entanto, na maioria dos casos, use o PrincipalPermission classe para controlar o acesso ao código com base na participação de identidade ou função.

O exemplo de código a seguir cria um WindowsPrincipal objeto e um WindowsIdentity o objeto, define-los para o usuário atual e toma uma decisão de segurança com base no valor da Principal. Ele não usa um PrincipalPermission objeto de forma declarativa ou imperativa, mas toma uma decisão de acesso com base nos valores do objeto principal em vez disso.

using System;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Principal;
using System.Threading;

public class Class1
{
    public static int Main(string[] args)
    {
        // Set principal policy to get a WindowsPrincipal 
        // as the current principal so you have permission to get 
        // current user information.
        AppDomain.CurrentDomain.SetPrincipalPolicy(
            PrincipalPolicy.WindowsPrincipal);

        // Get the current principal and put it into a principal object.
        WindowsPrincipal myPrincipal = (Thread.CurrentPrincipal 
            as WindowsPrincipal);

        // Check the name and see if the user is authenticated. 
        if (myPrincipal.Identity.Name.Equals(@"MYDOMAIN\myuser") 
            && myPrincipal.Identity.IsAuthenticated.Equals(true))
        {
            Console.WriteLine("Hello {0}, you are authenticated!", 
                myPrincipal.Identity.Name.ToString());
        }
        else
        {
            Console.WriteLine("Go away! You are not authorized!");
        }
        // Use IsInRole to determine the role of the current user.
        Array wbirFields = Enum.GetValues(typeof(WindowsBuiltInRole));
        foreach (object roleName in wbirFields)
        {
            try
            {
                Console.WriteLine("{0}? {1}.", roleName,
                    myPrincipal.IsInRole((WindowsBuiltInRole)roleName));
            }
            catch (Exception)
            {
                Console.WriteLine("{0}: Could not obtain role for this RID.",
                    roleName);
            }
        }
        return 0;
    }
}  
Imports System
Imports System.Security.Permissions
Imports System.Security.Policy
Imports System.Security.Principal
Imports System.Threading

Public Class Class1

    Public Shared Sub Main()
        ' Set principal policy to get a WindowsPrincipal 
        ' as the current principal so you have permission to get
        ' current user information.
        AppDomain.CurrentDomain.SetPrincipalPolicy( _
            PrincipalPolicy.WindowsPrincipal)

        ' Get the current principal and put it into a principal object.
        Dim MyPrincipal As WindowsPrincipal = _
            CType(Thread.CurrentPrincipal, WindowsPrincipal)

        ' Check the name and see if the user is authenticated. 
        If (MyPrincipal.Identity.Name.Equals("MYDOMAIN\myuser") _
            And MyPrincipal.Identity.IsAuthenticated) Then
            Console.WriteLine("Hello {0}, you are authenticated!", _
                MyPrincipal.Identity.Name.ToString())
        Else
            Console.WriteLine("Go away! You are not authorized!")
        End If
        ' Use IsInRole to determine the role of the current user.
        Dim wbirFields As Array = _
            [Enum].GetValues(GetType(WindowsBuiltInRole))

        Dim roleName As Object
        For Each roleName In wbirFields
            Try
                Console.WriteLine("{0}? {1}.", roleName, _
                    MyPrincipal.IsInRole(CType(roleName, _
                    WindowsBuiltInRole)))
            Catch
                Console.WriteLine( _
                    "{0}: Could not obtain the role for this RID.", _
                    roleName)
            End Try
        Next roleName
    End Sub
End Class

Se o usuário atual é MYDOMAIN\myuser, este programa exibe a seguinte mensagem no console.

Hello MYDOMAIN\myuser, you are authenticated!

No entanto, se qualquer outro usuário é o usuário atual, o programa exibe a seguinte mensagem de erro.

Go away! You are not authorized!

O valor em MyPrincipal.Identity.Name mostra o nome de usuário e domínio que representa a conta autorizados. Observe que a seqüência de caracteres C# "MYDOMAIN\myuser" é prefixado com no arroba (@) para que a barra invertida não seja interpretada como um caractere de escape. Embora o exemplo anterior usa um WindowsIdentity o objeto, você pode produzir facilmente o código semelhante usando um objeto genérico. Basta criar uma instância do objeto genérico, passe-os valores desejados e posteriormente verificar o objeto para esses valores.

Consulte também

Referência

System.Threading.Thread.CurrentPrincipal

Conceitos

Verificações de segurança baseada em função