Change Login Using Windows Authentication

Recently I had a need to allow users to change their login on an MVC site that used Windows authentication.  Of course we did not want the user to log out of their machine to do it.  The trick of course involved sending a 401 response, but how to do that and not get stuck in an endless loop.

The 401 Loop

It seemed simple enough, in fact too simple.  You just return a 401 challenge and have them move on to their previous page.  The 401 response is what presents the user with the Windows login popup.  In reality the 401 response acts like a redirect on itself, so you get two page loads and it forgets any variables you set.

Well that simply would not do.

The Fix

After thinking about it a bit I felt the best way was to use the Singleton Pattern.  The idea is to have an object that only allows one instance of itself in memory at a time.  If you do any kind of Unity game development you will know this well.

I created a class to make use of the singleton pattern.  I called it StatusKeeper.cs.

Putting it to Use

Finally all I needed to do was use this class in an action.  I made a simple controller action called ChangeLogin which returned an ActionResult.

Basically all I am doing is tracking the number of 401 responses sent to a specific user and determining what response to send back to them.  Users are identified by a GUID.


In summary that is how I did it.  It might not be perfect but it is simple and it works.  If you can improve on it, or know a better way by all means leave a comment.


About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on August 8, 2016, in .NET, C# and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: