Checking for access in a role
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security;
using System.Security.AccessControl;
using System.Security.Policy;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
public class MainClass
{
public static void Main()
{
IPrincipal user = Thread.CurrentPrincipal;
if (!user.IsInRole("Administrators"))
Console.WriteLine("User not in the "admin" role");
else
Console.WriteLine("User is an "admin"");
}
}
User not in the "admin" role
Declarative role-based security
using System;
using System.IO;
using System.Security.Permissions;
[PrincipalPermissionAttribute(SecurityAction.Demand, Role="Administrators")]
class MainClass
{
public static void Main()
{
FileStream fsOut = File.Create(@"c:\\temp\\test.txt");
StreamWriter sw = new StreamWriter(fsOut);
sw.WriteLine("str");
sw.Flush();
sw.Close();
}
}
Unhandled Exception: System.Security.SecurityException: Request for principal permission failed.
at System.Security.Permissions.PrincipalPermission.ThrowSecurityException()
at System.Security.Permissions.PrincipalPermission.Demand()
at System.Security.PermissionSet.DemandNonCAS()
at MainClass.Main()
The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.Permissions.PrincipalPermission
The first permission that failed was:
<IPermission class="System.Security.Permissions.PrincipalPermission, mscorlib, Version=2.0.0.0, Cult
ure=neutral, PublicKeyToken=b77a5c561934e089"
version="1">
<Identity Authenticated="true"
Role="Administrators"/>
</IPermission>
The demand was for:
<IPermission class="System.Security.Permissions.PrincipalPermission, mscorlib, Version=2.0.0.0, Cult
ure=neutral, PublicKeyToken=b77a5c561934e089"
version="1">
<Identity Authenticated="true"
Role="Administrators"/>
</IPermission>
The assembly or AppDomain that failed was:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089