Friday, November 19, 2004

Security Attributes in Microsoft.net

You can use windows credentials on any method you like by simple placing a Security Attribute on that method. In the code sample below I just used the user coscmasm which belongs to the LAB563 Domain. So, if you log in to your windows using coscmasm only than you can use the getName method.


using System;
using System.Security.Permissions;
using System.Security.Principal;

public class Foo
{
[PrincipalPermissionAttribute(SecurityAction.Demand, Name=@"LAB563\coscmasm")]
public void getName()
{
Console.WriteLine("This is coscmasm");
}
}
class App
{
static void Main()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(
PrincipalPolicy.WindowsPrincipal);
try
{
Foo f = new Foo();
f.getName();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

No comments: