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.
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.