Click here to Skip to main content
15,896,541 members
Articles / Web Development / HTML

ASP.NET - Forms authentication user impersonation

Rate me:
Please Sign up or sign in to vote.
4.63/5 (19 votes)
12 Nov 2009CPOL10 min read 122.1K   4.4K   55  
An ASP.NET class and accompanying control for providing application support users with a 'login as user ...' function the right way.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;

namespace System.Web.UI.WebControls
{

    /// <summary>
    /// The LoginUserImpersonation control presents a link button which will when clicked on revert user impersonation.
    /// When no user is being impersonated the LoginUserImpersonation controll will not be rendered.
    /// </summary>
    [ToolboxData("<{0}:LoginUserImpersonation runat=\"server\" ID=\"LoginUserImpersonation\" />")]
    public class LoginUserImpersonation : Control
    {

        #region Variables & Properties

        private LinkButton _deimpersonateLink;

        #endregion

        #region Functions

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _deimpersonateLink = new LinkButton();
            _deimpersonateLink.Click += new EventHandler(deimpersonateLink_Click);
            Controls.Add(_deimpersonateLink);

            // Hide the link button if no user is being impersonated.
            if (UserImpersonation.IsImpersonating)
            {
                _deimpersonateLink.Text = string.Format("Return to {0}", UserImpersonation.PrevUserName);
            }
            else
            {
                _deimpersonateLink.Visible = false;
            }
        }

        void deimpersonateLink_Click(object sender, EventArgs e)
        {
            if (UserImpersonation.IsImpersonating)
            {
                if (Deimpersonate != null)
                    Deimpersonate.Invoke(this, new EventArgs());

                UserImpersonation.Deimpersonate();
            }
        }

        /// <summary>
        /// The Deimpersonate event is invoked just before user impersonation is ended.
        /// </summary>
        public event EventHandler Deimpersonate;

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Netherlands Netherlands
Developer at AlertA contractbeheer.

Comments and Discussions