[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 840
  • Last Modified:

Wierd Problem with sessions! Session variables valid for some users and not for others

I am working on an application that uses session variables to pass values between the forms. The Application uses Active Directory Authentication for securities.

The application verifes if a user is valid in the global.asax file and then authenticates the user.

Now, when I run the application, I get an Null Reference Exception, on debugging I found that the Session Variable that was set on Page1 is not valid in Page2.

In the Page2 on Page Load I set a break point and in from the command window tried to get the Session Variable Value and I see this message..

"function 'Session.get_Item' evaluated and returned null"

In the Web.Config file Session State is as
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="1"/>

Now when I Set cookieless="true", I donot see this problem

I am using the HttpCookies in my code. Also, I have problem redirecting to a default page on session time out when I use cookieless="true"
0
srafi78
Asked:
srafi78
  • 8
  • 8
1 Solution
 
TornadoVCommented:
Can you post code that adds and retrieves your values to and from session?
0
 
srafi78Author Commented:
WebForm where the Session is set

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;

namespace POSystemReport
{
/// <summary>
/// Summary description for frmDefault.
/// </summary>
public class frmDefault : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lblAccessDenied;
protected System.Web.UI.WebControls.Label lblErrorMsg1;
protected System.Web.UI.WebControls.Label lblHeader;
protected System.Web.UI.WebControls.Label lblDefaultMsg;

private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
if (!((Request.Cookies.Get("isADMember")) == null))
{
lblErrorMsg1.Text = "Not a Valid Active Directory Member!";
return;
}
else
{
try
{
if (!((HttpContext.Current.User) == null))
{
Session["Fake"] = "1";
if (HttpContext.Current.User.IsInRole("CN=PO System Admin Group Role 1,CN=Users,DC=ad,DC=99only,DC=com"))
{
      Session.Add("uRoleID","1");
      Response.Redirect("frmInput.aspx", false);
}
else if (HttpContext.Current.User.IsInRole("CN=PO System Other Group Role 2,CN=Users,DC=ad,DC=99only,DC=com"))
{
      Session.Add("uRoleID", "2");
      Response.Redirect("frmInput.aspx");
}
else if (HttpContext.Current.User.IsInRole("CN=PO System Print Buyer Copy Group Role 3,CN=Users,DC=ad,DC=99only,DC=com"))
{
      Session.Add("uRoleID", "3");
      Response.Redirect("frmInput.aspx");
}
else if (HttpContext.Current.User.IsInRole("CN=PO System Print Receiving Copy Group Role 4,CN=Users,DC=ad,DC=99only,DC=com"))
{
      Session.Add("uRoleID", "4");
      Response.Redirect("frmInput.aspx");
}
else if (HttpContext.Current.User.IsInRole("CN=PO System Print Vendor Copy Group Role 5,CN=Users,DC=ad,DC=99only,DC=com"))
{
      Session.Add("uRoleID", "5");
      Response.Redirect("frmInput.aspx");
}
else if (HttpContext.Current.User.IsInRole("CN=PO System Print All Copies Group Role 6,CN=Users,DC=ad,DC=99only,DC=com"))
{
      Session.Add("uRoleID", "6");
      Response.Redirect("frmInput.aspx");
}
//if (HttpContext.Current.User.IsInRole("CN=PO System Test Group,CN=Users,DC=ad,DC=99only,DC=com"))
//{
//      Session.Add("uRoleID", "1");
//      Response.Redirect("frmInput.aspx");
//}
else
{
      lblErrorMsg1.Text = "You do not have access permissions to view the PO System Report";
}
      }
}
catch(System.Threading.ThreadAbortException thEx)
{
      //Do Nothing
}
}

}

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{    
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}

WebForm PageLoad where the Session Variable is accessed

private void Page_Load(object sender, System.EventArgs e)
{
if (Session.Count == 0)
{
try
{
      Response.Redirect("frmDefaultError.aspx", false);
}
catch (Exception ex1)
{
      Response.Write("Session Timed Out" + ex1.ToString());
}
}
// Put user code to initialize the page here

//If HttpContext.Current.User.IsInRole("CN=PO Receiving Reconciliation Buyer Group,CN=Users,DC=ad,DC=99only,DC=com") Then
if (
      HttpContext.Current.User.IsInRole("CN=PO System Admin Group Role 1,CN=Users,DC=ad,DC=99only,DC=com") ||
      HttpContext.Current.User.IsInRole("CN=PO System Other Group Role 2,CN=Users,DC=ad,DC=99only,DC=com") ||
      HttpContext.Current.User.IsInRole("CN=PO System Print Buyer Copy Group Role 3,CN=Users,DC=ad,DC=99only,DC=com") ||
      HttpContext.Current.User.IsInRole("CN=PO System Print Receiving Copy Group Role 4,CN=Users,DC=ad,DC=99only,DC=com") ||
      HttpContext.Current.User.IsInRole("CN=PO System Print Vendor Copy Group Role 5,CN=Users,DC=ad,DC=99only,DC=com") ||
      HttpContext.Current.User.IsInRole("CN=PO System Print All Copies Group Role 6,CN=Users,DC=ad,DC=99only,DC=com") ||
      HttpContext.Current.User.IsInRole("CN=PO System Test Group,CN=Users,DC=ad,DC=99only,DC=com")
)
{
//Proceed
}
else
{
Response.Redirect("frmDefault.aspx", false);
}

//clsSetFocus = new clsSetFocus;
clsSetFocus clsF = new clsSetFocus();

clsF.SetFocus(txtPONumber);

if(!Page.IsPostBack)
{

RoleID = Convert.ToInt32(HttpContext.Current.Session.Contents["uRoleID"]);


switch(RoleID)
{
      case 1:
            btnMaster.Enabled = true;
            btnVendor.Enabled = true;
            btnReceiving.Enabled = true;
            
            break;
      case 2:
            btnMaster.Enabled = true;
            btnVendor.Enabled = true;
            btnReceiving.Enabled = true;
            
            break;
      case 3:
            btnMaster.Enabled = true; //Print Master
            btnVendor.Enabled = false;
            btnReceiving.Enabled = false;
            
            break;
      case 4:
            btnMaster.Enabled = false;
            btnVendor.Enabled = true; //Print Receiving
            btnReceiving.Enabled = false;
            
            break;
      case 5:
            btnMaster.Enabled = true;
            btnVendor.Enabled = true;
            btnReceiving.Enabled = true; //Print Vendor
            
            break;
      case 6: //Print All copies
            btnMaster.Enabled = true;
            btnVendor.Enabled = true;
            btnReceiving.Enabled = true;
            
            break;

}

}

}

0
 
TornadoVCommented:
Try this:

RoleID = int.Parse(Session["uRoleID"].ToString());
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
srafi78Author Commented:
It Doesn't work

This is what is happenning
Page1
>? Session.SessionID
"205z4gf0f4umlsqy42jep455"

Page2
>? Session.SessionID
"zj2kvmrty0bm4b55eh2lpd45"

Is the Session not supposses to remain the same through out the application?
0
 
srafi78Author Commented:
OK, I see the problem when I am using the Windows Authentication, when I comment the code for AD authentication and then run the pages the session is valid across the page requests.

I am using almost exactly the same code as in http://www.codeproject.com/useritems/WindowsSecuritynASPNet.asp

0
 
TornadoVCommented:
Check out this article, http://forums.asp.net/7504/ShowPost.aspx , there is a huge section of FAQs regarding lost session variables.

Here is another article, it is dealing with a different kind of a problem but it might give you an idea:
http://www.velocityreviews.com/forums/t113713-losing-session-values.html
0
 
srafi78Author Commented:
I donot seem to figure out what the problem is.

I removed the Authentication code from the Global.asax and put the code in the Default Page PageLoad. Whenever there is a request to access the application it loads the Default Page and then redirects the User based on Access Level into the Application.
I did not use any Cookies in this event.

Set the Cookieless = false in the Web.config file and then ran the applicartion and it works fine for all users.

Now I go back to the Global.asax file and try using cookies for authentication, the application works fine for some users and the sessions are lost again for some users.

The GLobal.asax file contains the following code

public void Application_AuthenticateRequest(object sender, EventArgs e)
{

      if (!((Request.Cookies.Get("isADMember")) == null))
      {
            return;
      }
      else
      {
            HttpCookie httpCookADMember;
            httpCookADMember = new HttpCookie("isADMember", "N");
            Response.Cookies.Add(httpCookADMember);
      }
      System.Web.Security.FormsAuthenticationTicket formsAuthTicket;
      HttpCookie httpCook;
      GenericIdentity objGenericIdentity;
      string[] strRoles;
      httpCook = Context.Request.Cookies.Get("authCookie");
      formsAuthTicket = System.Web.Security.FormsAuthentication.Decrypt(httpCook.Value);
      objGenericIdentity = new GenericIdentity(formsAuthTicket.Name);
      strRoles = formsAuthTicket.UserData.Split(new char[] {'|'});
      HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(objGenericIdentity, strRoles);
}

protected void WindowsAuthentication_OnAuthenticate(object source, System.Web.Security.WindowsAuthenticationEventArgs e)
{
      if (!((Request.Cookies.Get("authCookie")) == null))
      {
            return;
      }
      string strUserIdentity;
      string strUserRoles;
      System.Web.Security.FormsAuthenticationTicket formsAuthTicket;
      HttpCookie httpCook;
      HttpCookie httpCookADMember;
      string strEncryptedTicket;

                strUserIdentity = e.Identity.Name.ToString();
      //strUserIdentity = "Domain99\\12345";            //User 1 Works Fine for him
      //strUserIdentity = "Domain99\\54321";            //User 2  does not Work for him
      
      bool IsExistInAD = new POSystemReport.clsADAuthorization().IsExistInAD(strUserIdentity);

      string UserName;
      UserName = new POSystemReport.clsADAuthorization().User(strUserIdentity);

      string GetADUserGroups = new POSystemReport.clsADAuthorization().GetADUserGroups(UserName);

      if (IsExistInAD == true)
      {

            strUserRoles = GetADUserGroups;
            formsAuthTicket = new System.Web.Security.FormsAuthenticationTicket(1, strUserIdentity, DateTime.Now, DateTime.Now.AddMinutes(60), false, strUserRoles);
            strEncryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(formsAuthTicket);
            httpCook = new HttpCookie("authCookie", strEncryptedTicket);
            Response.Cookies.Add(httpCook);
      }
      else
      {
            httpCookADMember = new HttpCookie("isADMember", "N");
            Response.Cookies.Add(httpCookADMember);
      }
}

I put breakpoints and see that for every request the cookies loose their value....

I think if I can retain the Cookies I can be good... How can this be done?
0
 
TornadoVCommented:
I have a couple of questions/suggestions:

Is your application running on a single server or on a web farm?
Is this a dedicated server or a shared (hosted) server?

Take a look in the Event Viewer under "System" and see if .NET is putting any errors in there. One possibility is your AppDomains are restarting for an unknown reason, once it is restarted your session data is gone, or there is too much info in the Session (which is probably not the case here).

Keep in mind that during the debugging modifying the Global.asax or the Web.Config file will cause the AppDomain to restart, immediately loosing all session data.

0
 
srafi78Author Commented:
The website is hosted on a shared server on the default port 80

Currently it is on my dev machine running on win xp sp2, I deployed it on the win 2003 server and saw the same problem, I will not be able to deploy it on a dedicated server as there are none available.

The Event Viewer under "System" and does not have any .NET errors.

but under the Applications I see this error donot know if this is the cause but

Type: Error
EventID: 1030
Source: Userenv

Description:
Windows cannot query for the list of Group Policy objects. A message that describes the reason for this was previously logged by the policy engine.

I donot know if this has something to do with the problem, but the problem reported is occurring with user level Manager and up.

0
 
TornadoVCommented:
I have another quick question, I'm looking at this:
HttpContext.Current.User.IsInRole("CN=PO System Admin Group Role 1,CN=Users,DC=ad,DC=99only,DC=com"), do you actually have a role called "CN=PO System Admin Group Role 1,CN=Users,DC=ad,DC=99only,DC=com" ?  Unless you have created all roles listed in your 'IFs' and have users added to those roles all your 'IF' statements will be false:

if (HttpContext.Current.User.IsInRole("CN=PO System Admin Group Role 1,CN=Users,DC=ad,DC=99only,DC=com"))
else if (HttpContext.Current.User.IsInRole("CN=PO System Other Group Role 2,CN=Users,DC=ad,DC=99only,DC=com"))
else if (HttpContext.Current.User.IsInRole("CN=PO System Print Buyer Copy Group Role 3,CN=Users,DC=ad,DC=99only,DC=com"))
else if (HttpContext.Current.User.IsInRole("CN=PO System Print Receiving Copy Group Role 4,CN=Users,DC=ad,DC=99only,DC=com"))
else if (HttpContext.Current.User.IsInRole("CN=PO System Print Vendor Copy Group Role 5,CN=Users,DC=ad,DC=99only,DC=com"))
else if (HttpContext.Current.User.IsInRole("CN=PO System Print All Copies Group Role 6,CN=Users,DC=ad,DC=99only,DC=com"))

Basically your Session.Add("uRoleID",#); never gets executed if you don't have at lease one of the above listed roles.
0
 
srafi78Author Commented:
All the groups are in place and have the appropriate users listed in them...
0
 
TornadoVCommented:
All IsInRole() is doing is a string check against the string you pass it:

//assuming that user is member of AD group called "domain\Role1"

bool present = HttpContext.Current.User("Role1");
if (present)
{
     Session.Add("uRoleID","1");
     Response.Redirect("frmInput.aspx", false);
}

else
{
     lblErrorMsg1.Text = "You do not have access permissions to view the PO System Report";
}
   
So unless you have an exact role called "CN=PO System Print All Copies Group Role 6,CN=Users,DC=ad,DC=99only,DC=com" then your IF is always returnes false.
0
 
srafi78Author Commented:
I suppose I was not clear enough, I have debugged the code and the if condition returns true assigning value "1" to the session variable uRoleID and then redirect to the Input Form. Now in the page load of the input form I see that uRoleID has no value...
0
 
TornadoVCommented:
Sorry, I just wanted to make sure.  By the way, your session timeout is set to 1, it expires after 1 minute.  Could that be an issue?
0
 
srafi78Author Commented:
I think I found what the issue was, the group list that I was getting from the Active Directory was having a very big size for users who were higher in level based upon their roles in the company, this big string was blowing up the cookie, every time an event was fired as the cookie size is limited as said in the msdn article under cookies limitations ... http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbtchASPNETCookies101.asp

So what I did was from the group list checked for the valid group membership and then returned it to be added to the cookie and the problem flew away. I think it was a size issue more than anything else....
0
 
TornadoVCommented:
I'm glad it worked out for you.  Regarding string size, as a rule of thumb we never actually store huge strings in cookies, just something really simple, like last time visit, user name, etc.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 8
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now