This problem yesterday lead Shawn to write this entry today – which I was just waiting for to appear online….
Whenever you get a SecurityException while running in partial trust (e.g. ASP.NET medium trust), you most probably won’t have the necessary permissions to look at the really important information in that Exception, e.g. which permission exactly was missing in my grant set.
As Nicole cleverly pointed out, you need to pass the exception to some code that has the necessary permissions (SecurityPermission/ControlPolicy and ControlEvidence that is), to extract the extended information. OK – cool. So i wrote this little helper class which asserts those permissions and returns the ToString() as well as the demanded and granted permission set:
using System;
using System.Security.Permissions;
using System.Security;
[assembly: AllowPartiallyTrustedCallers]
namespace LeastPrivilege
{
[
SecurityPermission(SecurityAction.Assert,
ControlEvidence=true, ControlPolicy=true)
]
public class SecurityExceptionViewer
{
public static string[] ViewException(SecurityException ex)
{
return new string[] {
ex.ToString(),
ex.Demanded.ToString(),
ex.GrantedSet.ToString()
};
}
}
}
Put this library in the GAC to call it from partially trusted code. This is how I found out that the general “request for SecurityPermission” error message really meant that the “Unmanaged Code” permission flag is missing. Very useful.
protected void Application_Error(object sender, EventArgs e)
{
try
{
Server.Transfer(“~/default2.aspx”);
}
catch (SecurityException ex)
{
string[] s = LeastPrivilege.SecurityExceptionViewer.ViewException(ex);
}
}
Needless to say that this tool is only meant for testing environments…