This is the line of code that I keep forgetting...
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
Use it in (for example) the Program.Main function when the application starts up and the threads currrent principal is now the windows user. So...
Thread.CurrentPrincipal.Identity.IsAuthenticated
Will now be
true and you can make use of the
Identity.Name property etc.
Self reminder over...
More Notes...If for example you need to perform unit tests as a windows user (to access the username or hit a resource) you can make use of the
AppDomain.CurrentDomain.SetPrincipalPolicy method in the test fixture setup/teardown methods - see example below. I put the UnauthenticatedPrincipal setting in the teardown so that subsequent tests do not have their principal modified by accident...
using System;
using System.Security.Principal;
using System.Threading;
using NUnit.Framework;
namespace Tests.SetPrincipalPolicyExample
{
[TestFixture]
public class TestSomethingUsingCurrentWindowsPrincipal
{
/// <summary>Called once before all tests are run.</summary>
[TestFixtureSetUp()]
public void TestFixtureSetUp()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
}
/// <summary>Called once after all tests have run.</summary>
[TestFixtureTearDown()]
public void TestFixtureTearDown()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal);
}
[Test]
public void VerifySomething()
{
string expectedUsername = Thread.CurrentPrincipal.Identity.Name;
// more testing stuff
}
}
}