Session in ASP is not storing values - asp-classic

I have two asp pages in the first page named verify.asp i have write this code:
verify.asp
<%
Username = Request.Form("loginx")
Password = Request.Form("passx")
liberado
Session("liberado") = Username
%>
in the second page i try to use the session variabel "liberado" with any result
barra.asp ,
<%
response.write(session("liberado"))
%>
What i'm making wrong? I m using chrome on IIS of windows 7, Username and Password have values

There was nothing really wrong with your code. Although I can see you've edited it now to remove the dim from liberado, but you've left liberado behind. This means your ASP will try and call a sub called liberado, which presumably doesn't exist. You can go ahead and remove that line.
<%
Dim Username, Password
Username = Request.Form("loginx")
Password = Request.Form("passx")
Session("liberado") = Username
%>
Trying to set a session whilst the session state is disabled will probably result in an error of some kind (and you didn't mention an error in your question). But make sure it's enabled by opening IIS and under ASP > Session Properties set "Enable Session State" to "True".
If it's already true then chances are there's something wrong with your form and the data isn't being posted. On your verify.asp page try running the following code:
for each item in request.form
response.write item & ": " & request.form(item) & "<br>"
next
This will output a list of all the form data being posted.
This could also be a cookie issue. If you're blocking cookies from being set in Chrome then there won't be an ASP session cookie, so session values won't be accessible as you move from page to page.
In Chrome press F12 to open developer tools, click the Applications tab, and from the "Cookies" drop down menu select your domain. Check there's an ASPSESSIONID cookie present, and it's the same cookie on both your ASP pages.

Check the application pool settings in IIS. If there are multiple worker processes active under "maximum worker processes", sessions don't always work. Sessions are stored per process, do if a different worker process handles the second request, the session from the first request might be missing. A setting of "0" means IIS uses as many processes as needed.
More information here

Related

Classic ASP dumping Session Variables (WITHOUT Authentication)

I have inherited an Classic ASP Site and a "bolt-on" ASP.NET site...
NEITHER are using Authentication, BOTH sides have a manual "reinvent-the- wheel" (hard-coded) security system that validates the user/pw from a SQL 2000 database (i.e. "if the user is found via a SQL SELECT, let them in").
New development is in ASP.NET... and they have "integrated" the two sites via ONE login (described above) on the Classic ASP side... then passing a GUID (saved at the time of login to the users record) they validate the GUID on the ASP.NET side ("yes, this is the correct GUID, therefore this is my user... let them in").
Up until now this has been working ONE DIRECTION (Classic ASP to ASP.NET) only with no issues.
(Getting to the problem, bear with me...)
Now they want to perform the same basic design from ASP.NET to Classic ASP by updating the GUID, passing it back, where the lookup validates the user, send them to the correct Classic ASP page... (so the user can return to the Classic ASP side without re-loging-in, previously required) HOWEVER...
***HERE's THE PROBLEM
Session("UserID") is used on the Classic ASP side to (hard code) validate the user... then Response.Redirect is run to send them back to the page that they previously left via "sRedirectToString" ...
'user is found in DB, so send them to the correct page...
Dim sRedirectToString = 'the correct url
Call Response.Redirect (sRedirectToString)
HOWEVER, Session("UserID") gets cleared by IIS or IE (dun'no) and the (hard-coded) validation fails because Session("UserID") is NULL (blank)
Here's the simple (only) validation:
If Trim(Session("UserID") & "") = "" Then
'Session timed out
Response.Redirect('the denied page)
Else
Response.Write "<meta http-equiv=""X-UA-Compatible"" content=""IE=EmulateIE7"">"
End If
So, why are the Session Variables being cleared by a Redirect? (there is no other system authentication is being used).
There is no Session.Abort, nor any specific coding that is clearing Session("UserID").
But when Session("UserID") is tested (see code above) it is found empty and redirects to the DENIED.asp page.
So, hoping there is some property like "PersistSessionVariables" (or something) that I can set so they don't clear...
BUT THEY DO INDEED CLEAR IMMEDIATELY AFTER THE REDIRECT AND THIS IS CONFUSING TO ME.
I appreciate all the Wizards help!

Why would Session_Start keep reloading without firing Session_End

I am having trouble tracking down why the session keeps restarting in a web app.
I have placed code in both the Session_End or Application_End procedures to try and track what is happening, but neither of these two procedures are reached in code before the session restarts and fires the Session_Start procedure again.
Does any know what would cause the Session_Start procedure to restart without firing the Session_End or Application_End procedures?
Basically, there is code in the Session_Start that sets session variables and code in the Session_End that tries to log why the session ended
There are 100 or more aspx pages with VB code behind them all on the web site, and it looks like the session restarts randomly, sometime up to 3 times while loading the home page. I have a break set in the global.asax page inside the Session_Start procedure and it breaks there so I can tell when it reloads and loses all the session variables set in any of the ASPX page code behind.
I know some common causes like writing to certain files or folders like the App_Data folder, and the app pool being recycled, but I can not seem to track down why this is happening when Session_End or Application_End never fire and I cannot log the reason it ended.
I inherited this "project" and I "winging" my way through the code at this point so thanks you for any help you can give me on this ...
the server is IIS7, running ASP.NET and the code is in VB.NET, I have also included ' sessionState mode="InProc" ' in the web.config file to make sure the session procedures will be used.
This is VB code in the Session_Start procedure
HttpContext.Current.Session.Item("SessionMessageView") = "no"
HttpContext.Current.Session.Item("DefaultMenuName") = "Default"
HttpContext.Current.Session.Item("RootVirtualPath") = "/"
HttpContext.Current.Session.Item("BlockerTested") = False
HttpContext.Current.Session.Item("BlockerTurnedOn") = False
HttpContext.Current.Session.Item("IsMobileBrowser") = False
This is VB code in both the Session_End and Application_End procedures
Dim runtime As HttpRuntime = DirectCast(GetType(System.Web.HttpRuntime).InvokeMember("_theRuntime", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.[Static] Or System.Reflection.BindingFlags.GetField, Nothing, Nothing, Nothing), HttpRuntime)
If runtime Is Nothing Then
Return
End If
Dim shutDownMessage As String = DirectCast(runtime.[GetType]().InvokeMember("_shutDownMessage", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.GetField, Nothing, runtime, Nothing), String)
Dim shutDownStack As String = DirectCast(runtime.[GetType]().InvokeMember("_shutDownStack", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.GetField, Nothing, runtime, Nothing), String)
If Not System.Diagnostics.EventLog.SourceExists(".NET Runtime") Then
System.Diagnostics.EventLog.CreateEventSource(".NET Runtime", "Application")
End If
Dim log As New System.Diagnostics.EventLog()
log.Source = ".NET Runtime"
log.WriteEntry([String].Format(vbCr & vbLf & vbCr & vbLf & "_shutDownMessage={0}" & vbCr & vbLf & vbCr & vbLf & "_shutDownStack={1}", shutDownMessage, shutDownStack), System.Diagnostics.EventLogEntryType.[Error])
If I could only figure out why the Session_End procedure is not firing while the Session_Start procedure fires multiple time I might be able to track down the why the session is restarting.
See this question regarding Session_Start : Session_Start firing multiple times on default ASP.NET MVC3 project
Note that Session_End will never run if you are using SQLServer session state storage, or indeed anything other than InProc mode in your web.config sessionState directive.
With help from James I have discovered the problem. New code was added to determine if the user's browser accepts cookies and then it was being tested with cookies disabled. When cookies are enabled this does not happen and the session does not restart. It seems that when cookies are not accepted by a browser, and you try to store a cookie on that browser, it caused the session to restart because of the error without firing End_Session!
Now I guess we will have to rethink the cookie test and figure a way to store a flag that is somehow linked to the user and can indicate if cookies are accepted without trying to store a cookie on the user's machine ... hmmmm
Thank you all for your assistance on this ... sometimes it's the small things that trip you up ... I am reminded of the saying that an increase in bugs is proportional to changes in code

Classic ASP: ASPSessionID is reused

I know how to handle this in ASP.NET, but is there a way to force the Classic ASP Session ID to be cleared? It is a randomly generated ID like ASPSESSIONIDG32423E that does not seem to be available in RESPONSE.COOKIES collection thus I can not clear it. We have a class ASP site still hanging around and recently it was an audit finding that after the user logs out the same session ID is reused.
MORE CLARIFICATION:
First visit to page, I see this in the proxy editor in Response:
Set-Cookie: ASPSESSIONID=PUYQGHUMEAAJPUYL; path=/Webapp
After a logout, I call Session.RemoveAll and Session.Abandon and then redirect user to login page. At which point I should see a new Set-Cookie with a different value for SessionID. Instead, I do not get a new cookie and the new login session reuses the original session cookie. This is an audit finding that we have to resolve in some way but there does not seem to be a way to control this.
So I did come up with a solution for this as follows. I added two pages called Start.asp and Start2.asp. The original login page was changed to check for a post variable which is now set on Start2.asp, so if login.asp does not see that post variable, it redirects to Start.asp. Start.asp invalidates the ASPSessionID by setting it to 0. The key is using Response.AddHeader "Set-Cookie" in order to do this since Response.Cookies("ASPSESSIONID...") gives an error that you can't access the element:
Code for Start.ASP
<%
If instr(Request.ServerVariables("HTTP_COOKIE"), "ASPSESSIONID") > 0 Then
Dim Allcookies
AllCookies = Split(Request.ServerVariables("HTTP_COOKIE"),";")
For i = 1 to UBound(AllCookies)
If instr(AllCookies(i), "ASPSESSIONID") > 0 Then
Response.AddHeader "Set-Cookie", Left(AllCookies(i),instr(AllCookies(i),"=") -1) & "=0; path=/;secure;httponly"
End if
Next
End if
Response.Redirect("start2.asp")
%>
Next, it calls Start2.asp which looks for all ASPSEssionID cookies and appends Secure; httponly (I had to add these for another finding, ASP metabase setting to add secure only works if the SSL cert. is on the web server. In our case the SSL cert is on a load balancer in front of the web server).
Code for Start2.asp
<%
'CODE for authorization/authentication
'...
Session.Contents.RemoveAll
Session.Abandon
If instr(Request.ServerVariables("HTTP_COOKIE"), "ASPSESSIONID") > 0 Then
Dim Allcookies
AllCookies = Split(Request.ServerVariables("HTTP_COOKIE"),";")
For i = 1 to UBound(AllCookies)
if left(Request.ServerVariables("HTTP_HOST"),2) = "65" and instr(AllCookies(i), "ASPSESSIONID") > 0 Then
Response.AddHeader "Set-Cookie", AllCookies(i) & "; path=/;secure;httponly"
End if
Next
End if
%>
<html>
<body>
<form action="login.asp" method="post">
<input type="hidden" name="start2" id="start2" value="Yes" />
</form>
<script type="text/javascript">
document.forms[0].submit();
</script>
</body>
</html>
Really, though, the new ASPSessionID is not generated until within Start2.asp so that Set-Cookie code for secure and httponly has to also be done in login.asp. So the same code above was copied to the top of login.asp just after this code:
If request.form("Start2") = "" Then
Response.Redirect("start.asp")
End if
IMO - you need to end the session rather than just clear out the session ID. In this case, Session.Abandon is the solution. Ref.: https://devguru.com/content/technologies/asp/session-abandon.html
HTH.
This relates to ASP.NET but describes the behaviour you are seeing in ASP
When you abandon a session, the session ID cookie is not removed from
the browser of the user. Therefore, as soon as the session has been
abandoned, any new requests to the same application will use the same
session ID but will have a new session state instance.
http://support.microsoft.com/?kbid=899918
This behaviour will only occur if using the same browser for the same session, as soon as the browser is closed the session cookie will be lost (providing an explicit expiry date has not been set).
You could try calling Session.Abandon then redirect the user to a page which uses JavaScript to clear all cookies, then redirect to the login page, or whatever page you like.
Clearing all cookies with JavaScript

Losing Session between Classic ASP and ASP.NET

The company that I work for is making a transition between classic ASP programs and ASP.NET programs for our intranet software. Eventually, everything will be written in ASP.NET, but because of time constraints, there are still a number of programs that use classic ASP.
To compensate we've written features that allow for redirects and autologins between classic ASP programs and ASP.NET programs. I've been starting to see a problem, though, with holding the session state for our ASP.NET software. If a user uses an ASP.NET program, then does work in a classic ASP program, then goes back to that ASP.NET program, often times, the user's authentication for the ASP.NET program is still in place, yet the user's session is lost, resulting in an error whenever a function is performed within the program.
I'm trying to capture the loss of the session state in global.asax's Session_End event, which would redirect the user to the login page, but that hasn't worked. Has anyone else faced a similar issue with users moving back and forth between classic ASP and ASP.NET and losing sessions? Is that even my real issue here? It's the only thing that I can see as being a problem.
EDIT
This is what we do to redirect users to an ASP.NET page from a classic asp page.
We create an MD5 hash based off of the userID and the date and send it to a redirect.aspx page via the query string. From there, the aspx page creates its own MD5 has based off of the userId and the date, both passed via the query string. If the 2 hashes are identical, the user is authenticated, and the program loads. Here is an example:
Classic ASP:
strDate = Year(Now()) & right("0" & Month(Now()), 2) & right("0" & Day(Now()), 2)
key = MD5(SessionUserID & strDate)
Response.Redirect "/redirect.aspx?key="&key&"&lpid="&ProgramID&"&unum="&SessionUserNum&"&uid="&SessionUserID&"&gid="&SessionGroupID
Redirect.aspx:
string key = Request.QueryString["key"];
//SetDesignModeState Variables:
if (getMd5Hash(Request.QueryString["uid"] + DateTime.Today.ToString("yyyyMMdd")) == key)
{
Session["SessionGroupID"] = Request.QueryString["gid"];
Session["SessionUserNum"] = Request.QueryString["unum"];
Session["SessionUserID"] = Request.QueryString["uid"];
string appID = Request.QueryString["lpid"];
FormsAuthentication.SetAuthCookie(Request.QueryString["uid"], false);
//redirect to ASP.NET page...
I've done a similar thing to you: authenticating users from a legacy ASP application to an ASP.NET site. What would help, is if you could provide a little more detail (sample code, perhaps) of the process you've setup to do this with users coming from the legacy app to the ASPX app.
To give you a brief idea, in my implementation I've done the following:
Create an .ASPX page
The .ASPX page accepts HTTP POST values from a particular legacy ASP app only.
When a POST request is received, I extract the username/password values, then proceed to authenticate in the normal way. If the user is successfully authenticated, we issue a FormsAuthentication cookie to the user.
In reality, my implementation is quite a bit more complicated, using the database as a backing store (as both apps share a common data source) and a particular database field to store a random code which is sent from the classic app to the .NET side to further verify that the request received by the .NET app is valid.
EDIT:
Try manually setting your authentication cookie. Delete the line:
FormsAuthentication.SetAuthCookie(Request.QueryString["uid"], false);
Replace with:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
Request.QueryString["uid"],
DateTime.Now,
DateTime.Now.AddHours(24),
false,
null)
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.Cookies.Add(cookie);
See how you get on with that?

Cookies NULL On Some ASP.NET Pages (even though it IS there!)

I'm working on an ASP.NET application and I'm having difficulty in understanding why a cookie appears to be null.
On one page (results.aspx) I create a cookie, adding entries every time the user clicks a checkbox. When the user clicks a button, they're taken to another page (graph.aspx) where the contents of that cookie is read.
The problem is that the cookie doesn't seem to exist on graph.aspx. The following code returns null:
Request.Cookies["MyCookie"];
The weird thing is this is only an issue on our staging server. This app is deployed to a production server and it's fine. It also works perfectly locally.
I've put debug code on both pages:
StringBuilder sb = new StringBuilder();
foreach (string cookie in Request.Cookies.AllKeys)
{
sb.Append(cookie.ToString() + "<br />");
}
this.divDebugOutput.InnerHtml = sb.ToString();
On results.aspx (where there are no problems), I can see the cookies are:
MyCookie
__utma
__utmb
__utmz
_csoot
_csuid ASP.NET_SessionId
__utmc
On graph.aspx, you can see there is no 'MyCookie'
__utma
__utmb
__utmz
_csoot
_csuid ASP.NET_SessionId
__utmc
With that said, if I take a look with my FireCookie, I can see that the same cookie does in fact exist on BOTH pages! WTF?!?!?!?! (ok, rant over :-) )
Has anyone seen something like this before? Why would ASP.NET claim that a cookie is null on one page, and not null on another?
This was happening because I was running the app under a different virtual directory. When I ran it on the original one, it worked.
I would suggest loading the IIS debug diagnostics tools. It is entirely possible that on that particular server there is a resource problem or unhandled exception that is killing that particular cookie AFTER it is added to the response but before it is flushed to the user. This is basically caused by a series of exceptions that occur in rapid succession causing rapid fail protection to shut down the w3wp.exe process that your page is running under. When the process is spooled back up to feed the response, the cookie is gone and all that goes out is the rendered html.
You might also try turning off rapid fail protection or altering memory settings/recycling settings on the application pool.

Resources