次の方法で共有


プリンシパル オブジェクトへの直接アクセス

強制的な確認要求や宣言的な確認要求を使用してロール ベース セキュリティ チェックを呼び出すのが、ID とロール メンバシップをチェックおよび強制するときに通常に使用される方法ですが、場合によっては、Principal オブジェクトとそれに関連付けられている Identity オブジェクトに直接アクセスして、許可オブジェクトを作成せずに承認タスクを行うこともあります。たとえば、例外のスローを検証が失敗したときの既定の動作としない場合は、宣言的な確認要求や強制的な確認要求を使用しません。この場合は、System.Threading.Thread クラスで静的な CurrentPrincipal プロパティを使用して Principal オブジェクトにアクセスし、そのメソッドを呼び出すことができます。

プリンシパル オブジェクトを取得した後、条件文を使用することによって、コードへのアクセスをプリンシパル名に基づいて制御できます。この方法を次のコード例で示します。

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

また、現在の Principal オブジェクトで IsInRole メソッドを呼び出すことによって、ロール メンバシップをプログラム的に確認することもできます。この方法を次のコード例で示します。

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

この方法は、アプリケーション定義の Principal オブジェクトに固有な動作にアクセスするときに使用できます。ただし、ほとんどの場合は、PrincipalPermission クラスを使用して、ID またはロール メンバシップに基づいてコードへのアクセスを制御します。

次のコードでは、WindowsPrincipal オブジェクトと WindowsIdentity オブジェクトを作成し、これらを現在のユーザーに設定し、Principal の値に基づいてセキュリティ決定を行います。このコードでは、強制的または宣言的に PrincipalPermission オブジェクトを使用せずに、プリンシパル オブジェクトの値に基づいてアクセス決定を行います。

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

現在のユーザーが MYDOMAIN\myuser の場合、このプログラムは次のメッセージをコンソールに表示します。

Hello MYDOMAIN\myuser, you are authenticated!

他のユーザーが現在のユーザーである場合は、次のメッセージが表示されます。

Go away! You are not authorized!

MyPrincipal.Identity.Name の中の値は、承認されたアカウントを表すドメインとユーザー名を示します。C# では、円記号がエスケープ文字として解釈されないように、文字列 "MYDOMAIN\myuser" の先頭にアット マーク (@) が付けられます。前の例では WindowsIdentity オブジェクトを使用していますが、汎用オブジェクトを使用しても同様のコードを簡単に作成できます。汎用オブジェクトのインスタンスを作成し、必要な値を渡し、これらの値について後でオブジェクトを確認するだけです。

参照

関連項目

System.Threading.Thread.CurrentPrincipal

概念

ロール ベース セキュリティ チェック