Acessando diretamente um objeto entidade de segurança de segurança

Embora o uso de demandas imperativas e declarativas para invocar as verificações de segurança baseada em função seja o entidade de segurança de segurança mecanismo para verificar e aplicar a identidade e associação da função, pode haver casos em que você deseja acesso o entidade de segurança de segurança objeto e seus associados Identidade objeto diretamente para executar tarefas de autorização sem criar objetos de permissão.Por exemplo, não convém usar demandas declarativas ou imperativas, se você não quiser que uma exceção gerada para ser o comportamento padrão para falha de validação.Nesse caso, você pode usar o estáticoCurrentPrincipal propriedade a System.Threading.Thread o acesso de classe a entidade de segurança de segurança objeto e chamar seus métodos.

Depois de obter o objeto, você pode usar instruções condicionais para controle acesso ao seu código com base no nome do entidade de segurança de segurança, sistema autônomo neste 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ê pode verificar também programaticamente associação em funções, chamando o IsInRole método no corrente entidade de segurança de segurança 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 esta técnica quando você deseja acessar comportamentos específicos para um aplicativo definido entidade de segurança de segurança objeto.No entanto, na maioria dos casos, você usar o PrincipalPermission classe para controlar o acesso ao seu código com base na identidade ou associação da função.

O exemplo de código a seguir cria um WindowsPrincipal objeto e um WindowsIdentity objeto define-os ao usuário corrente e toma uma decisão de segurança com base no valor da entidade de segurança de segurança.Ela não usa um PrincipalPermission objeto forma declarativa ou imperativa, mas torna uma decisão de acesso com base nos valores do objeto entidade de segurança de segurança 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 corrente for MYDOMAIN\myuser, este programa exibe a seguinte mensagem ao console.

Hello MYDOMAIN\myuser, you are authenticated!

No entanto, se qualquer Outros usuário é o usuário corrente, o programa exibirá a seguinte mensagem.

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 autorizada. Observe que a seqüência de caracteres translation from VPE for Csharp"MYDOMAIN\myuser" é prefixado com arroba (@), para que a barra invertida não seja interpretada sistema autônomo um caractere de escape. Embora o exemplo anterior usa um WindowsIdentity objeto, você pode produzir com com facilidade usando um objeto genérico de código semelhantes.Simplesmente criar uma instância do objeto genérico, passar os valores desejados e verificar o objeto para os valores mais tarde.

Consulte também

Conceitos

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

Referência

sistema.Threading.Thread.CurrentPrincipal