Run a Windows Forms application as the Windows User - Integrated Security

by Paul Kohler 18. May 2007 09:32
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
        }
    }
}


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

General

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.10
Theme by Mads Kristensen