Partager via


Accès direct à un objet Principal

L'utilisation de demandes impératives et déclaratives pour l'appel de contrôles de sécurité basés sur les rôles constitue le mécanisme principal pour la vérification et l'implémentation des identités et l'appartenance aux rôles. Toutefois, dans certains cas, vous pouvez accéder directement à l'objet Principal et l'objet Identity qui lui est associé afin de réaliser des tâches liées aux autorisations, sans créer d'objets d'autorisation. Ainsi, vous préférerez peut-être ne pas utiliser de demandes déclaratives ou impératives pour éviter qu'une exception soit levée par défaut en cas d'échec de la validation. Dans ce cas, vous pouvez utiliser la propriété statique CurrentPrincipal sur la classe System.Threading.Thread pour accéder à l'objet Principal et appeler ses méthodes.

Après obtention de l'objet Principal, vous pouvez utiliser des instructions conditionnelles pour contrôler l'accès à votre code, en fonction du nom de l'entité de sécurité, comme illustré dans l'exemple de code suivant.

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

Vous pouvez également effectuer un contrôle par programme de l'appartenance à des rôles en appelant la méthode IsInRole sur l'objet Principal en cours, comme illustré dans l'exemple de code suivant.

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

Cette méthode peut être utile pour accéder aux comportements spécifiques d'un objet Principal défini par une application. Toutefois, dans la plupart des cas, vous utiliserez la classe PrincipalPermission pour contrôler l'accès à votre code en fonction de l'identité ou de l'appartenance à un rôle.

L'exemple de code suivant crée un objet WindowsPrincipal et un objet WindowsIdentity, les définit sur l'utilisateur actuel et prend une décision de sécurité à partir de la valeur de l'objet Principal. Il n'utilise pas l'objet PrincipalPermission de manière impérative ou déclarative, mais accorde une autorisation d'accès en se basant sur les valeurs de l'objet Principal.

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

Si l'utilisateur en cours est MYDOMAIN\myuser, ce programme affiche le message suivant dans la console.

Hello MYDOMAIN\myuser, you are authenticated!

Toutefois, s'il s'agit d'un autre utilisateur, le programme affiche le message suivant.

Go away! You are not authorized!

La valeur de MyPrincipal.Identity.Name indique les noms de domaines et d'utilisateurs qui représentent le compte autorisé. Notez que, en C#, la chaîne "MYDOMAIN\myuser" est précédée du symbole (@) afin que la barre oblique inverse ne soit pas interprétée en tant que caractère d'échappement. Bien que l'exemple précédent utilise un objet WindowsIdentity, vous pouvez aisément générer le même code à l'aide d'un objet générique. Il vous suffit pour cela de créer une instance de l'objet générique, de lui passer les valeurs requises, puis de vérifier que l'objet a bien ces valeurs.

Voir aussi

Référence

System.Threading.Thread.CurrentPrincipal

Concepts

Contrôles de sécurité basés sur les rôles