Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lost session/cookie when login as another user

I am building dnn module which allow logged in user to log in as another user.
But I have some wired issue here.
This is how I log out current user and login as another user:

UserInfo userInfo = UserController.GetUserById(portalId, userId);
if (userInfo != null)
{                
    DataCache.ClearUserCache(this.PortalSettings.PortalId, Context.User.Identity.Name);

    if (Session["super_userId"] == null)
    {
        Session["super_userId"] = this.UserId;
        Session["super_username"] = this.UserInfo.Username;
    }

    HttpCookie impersonatorCookie = new HttpCookie("cookieName");
    impersonatorCookie.Expires = DateTime.Now.AddHours(1);
    Response.Cookies.Add(impersonatorCookie);

    Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
    Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;

    PortalSecurity objPortalSecurity = new PortalSecurity();
    objPortalSecurity.SignOut();

    UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);

    Response.Redirect(Request.RawUrl, true);
}

And in PageLoad() I try to read value from this cookie but it doesn't read anything:

try
{
    string super_userId = Request.Cookies["cookieName"]["super_userId"];
    string super_username = Request.Cookies["cookieName"]["super_username"];

    if (!String.IsNullOrEmpty(super_userId))
    {
        this.Visible = true;
        this.lblSuperUsername.Text = Session["super_username"].ToString();
        this.txtPassword.Enabled = true;
        this.btnBackToMyAccount.Enabled = true;
    }
...

I also have tried to do the same with session but nothing works, and I can't figure why?

like image 992
1110 Avatar asked Apr 21 '26 17:04

1110


1 Answers

As I find here, there can be problems with setting cookies in a request that gets redirected, and here is stated that cookies won't get set with a redirect when their domain is not /.

So you can try to not redirect using HTTP headers, but show a "Logged In" page instead that contains a "Home" link and a meta refresh or Javascript redirect.

By the way, setting a UserID in a cookie is not really the way to go. What if I change that cookie value to 1?

like image 82
CodeCaster Avatar answered Apr 23 '26 06:04

CodeCaster