Is there any way to retrieve the SSL session Id serverside in asp.net?
the short answer is no. This is an intentional limitation of IIS, so as to prevent people from taking a dependency on something that isn't dependable.
Out on the market, you will find various hardware load-balancers that will offer features like server persistence based on SSL Session ID, but they don't work very well because SSL renegotiation can happen at any time. In Internet Explorer 8, for example, a new SSL session is negotiated for every tab that is opened to a web site. You can expect similar behaviour from other multi-process browsers. So, I must stress that you should not use SSL Session ID for any kind of user identification purposes.
That said -- If you really need the SSL Session ID information for some specialized task, I recommend using Apache, mod_ssl and mod_proxy as a front-end to your IIS system. With a bit of fiddling, you could coerce mod_ssl into giving you the session ID, which you could then add to a proxied request to your IIS server as a query string parameter.... or you could store it in a database.
Tim,
Are you really "just" trying to retrieve the Session ID string or do you maybe lose all session information when switching to SSL? this would be a quite common problem, because the session on serverside is lost when using "InProc" session storage, and the session cookie on the client might be lost when not stored in a common domain.
Therefore, you should switch to state server or sql server session management in Web.config file, for example:
<sessionState mode="SQLServer"
cookieless="true"
regenerateExpiredSessionId="true"
timeout="30"
sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;"
stateNetworkTimeout="30" />
Beside that, I don't really know why you shouldn't be able to retrieve HttpContext.Current.Session.SessionID also in SSL mode as well.
Some MSDN Links:
MSDN: HttpSessionState.SessionID Property
MSDN: ASP.NET Session State Overview
Maybe this helps somehow.
Best regards
Related
When user login i am storing user_id in Session variable and on second page i am checking on page load if user_id exists then fine, otherwise redirect to sign in page but when i login and and redirected to next page after few seconds when i refresh page my session is null there and i am redirected to sign in page its happening in whole application i have tried all solutions but all in vain
Another thing is that application working fine on development server and also on local IIS in LAN but on live server this issue is occurring.
Kindly suggest solution, i am also defining session time out in minutes and mode in Proc in web.config.
Thanks in advance
If you are using InProc session state mode and multiple worker processes in the application pool then Session might expire automatically after few seconds as data loss can occur if different requests for the same session are served by different worker processes.
In my case, I am using InProc session state mode with Maximum Worker Process set to 4 hence session was expiring.
Setting Maximum Worker Process = 1 solved it.
You can add <httpRuntime delayNotificationTimeout=""/> in your web.config. see more
OR
Try this
<authentication mode="Forms">
<forms loginUrl="/loginurl" timeout="2880" />
</authentication>
try this in web.config
<configuration>
<system.web>
<sessionState mode="InProc" timeout="90"></sessionState>
</system.web>
</configuration>
One session issue I just ran into, which may help here, is that users from certain companies would have their sessions end fairly quickly but other users had no problem. After doing a lot of testing, I found that users connecting to the website from their office were having problems but the same user connecting from home had no problem.
Their company is setup to use a single IP (or set of IPs) for all out bound web requests. Well, this company had multiple IPs for out-site access and that IP changed (or could change) with each request. This would reset the session on my website and log them out.
I am still in the process of implementing a fix or a check for this so I can't give you a fool proof fix, but it is something to look into. This would explain what is happening to you.
Any chance you're using a cluster of servers? Network load balancing might reroute the client to a different server every time. If so, either the NLB has to be reconfigured to keep a client on a single server or set up session sharing.
Also check that the application pool doesn't have some obscene rule to recycle itself too often.
In my asp.net application I have a few session variables. Seems like only a few minutes on the localhost and also web host, they lose value. This happens periodically not all of the time. I do have cheap go daddy, web hosting, and that could be the problem on the web server. Thank you for any help, this is a big problem.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="3600" defaultUrl="~/" name="" />
</authentication>
<sessionState mode="InProc" cookieless="false" timeout="80" />
public static User User
{
get
{
User userLogin = null;
object sessionVar = Session[USERLOGIN];
if (sessionVar != null)
{
userLogin = (User) sessionVar;
}
return userLogin;
}
set { Session[USERLOGIN] = value; }
}
There's a strong chance that your session is being wiped out on the server from the application pool being stopped and started, timeouts, or a host of other things. The main point is that session variables solely by themselves are unreliable persistent mechanisms.
If you need information to persist for a logged in user, try storing a cookie on the user's machine and if the session is null, repopulate it from identifying data in the cookie.
If I could comment I would, apparently I am not special enough ;P lol. I have to agree with KodeKreachor and Aristos on both points. I am not sure why there is a business/reasonable need to have the session state kept in memory.
To add to the points, mostly because I hate cookies, you could roll a solution to keep session states logged in a light weight database. I mean it really is all a cookie is for, flat file database record of information. SQLite might be a good solution, though unless I can find otherwise, you are rolling your own solution on that. Yes, as a loving Godaddy supporter, their cheaper services have a LOT to be desired. There is little to no control over what the system is doing with their shared hosting. My experience of hours talking to their tech department about what is and is not allowed can tell you that.
I would also mention that you might want to add some very verbose logging into the system using a solution such as Log4Net and then parse the logs for information on what is actually happening when the session state is being wiped. Then armed with that information move forward to find a much more clear solution.
Or just go easy on yourself and use cookies ;)
Just modify this for SQLite =D
HOW TO: Configure SQL Server to Store ASP.NET Session State
Of course here is a SQLite Session State Provider
SQLiteSessionStateStore
Apache Log4Net
Great Tutorial Series on using Log4Net by BeefyCode
It seems like there are a lot of ways but no default. For State management, does ASP.NET use cookies by default?
If so, what are the alternatives to using cookies?
If not, what does ASP.NET use by default to manage state?
Yes - by default, ASP.NET uses cookies to maintain session.
That is, a unique "Session Identifier" cookie is stored on the client to keep track of sessions on the server (state service, sql db, etc).
But in the web.config, you can set cookieless to true:
<sessionState mode="InProc" cookieless="true" timeout="20" />
This will cause that very same "Session Identifier" to be stuck in the URL, and no cookies will be used.
Don't get confused though - the cookies dont store the actual "session". It sounds like you think cookies can be used as an alternative to something like the ASP.NET state service.
When in fact, the cookie just stores an identifer in order to "track" the session, in other words - this "identifier" is passed between the client-server on every HTTP request, this way the server can synchronize a particular session item with the client it belongs to.
Cookie-based/Cookieless session is irrespectible of what actual state storage mechanism you have in place - whether it be In Process session, ASP.NET State Service or SQL Server. It simply dictates the way in which the server is allowed to keep track of sessions.
Of course, cookieless sessions will suit clients that are likely to turn cookies off, but the disadvantage of this is you have ugly URL's, but this can be negated quite easily with the use of URL rewriting, although i would recommend against this - many have reported problems in attempting to do so.
HTH
I'm working on an ASP.NET MVC web application that will be deployed across multiple load-balanced servers. With this setup, a user might have one request served by server A and the next request will be served by ServerB or ServerC.
We don't want to store Session Data in the database, as we're trying to minimise database hits where ever possible. As such, we need to have the HttpSession managed and stored on another server.
My understanding is that this is possible by using a Windows Service that will manage this for me, but I'm unfamiliar with how to implement this. Can somebody point me at some good documentation on how to do this? Or any pitfalls or other points to take into consideration? Thanks
You need to dedicate a machine that will host the Windows NT service and which must have .NET installed (well you could use one of the web servers as state server but IMHO this would be a very bad idea):
net start aspstate
And then instruct your application to use this server:
<system.web>
<sessionstate
mode="stateserver"
cookieless="false"
timeout="20"
server="127.0.0.1"
port="42424"
/>
</system.web>
where of course you would replace 127.0.0.1 with the IP address of the server hosting the NT service.
Note1: don't forget to decorate the objects you intend to store into session with the [Serializable] attribute.
Note2: this is a good solution in a load balanced environment but if you are looking for a real failover clustering you should use SQL server.
You may read more details about ASP.NET session state on MSDN.
As usual, Peter gives this issue good coverage...
http://www.eggheadcafe.com/articles/20021016.asp
Another alternative you may want to consider is Memcached Providers - it allows you to store session state in a memcached instance; optionally using SQL Server as a fallback. The best of both worlds, IMHO.
My forms are losing session variables on shared hosting very quickly (webhost4life), and I think I want to replace them with cookies. Does the following look reasonable for tracking an ID from form to form:
if(Request.Cookies["currentForm"] == null)
return;
projectID = new Guid(Request.Cookies["currentForm"]["selectedProjectID"]);
Response.Cookies["currentForm"]["selectedProjectID"] = Request.Cookies["currentForm"]["selectedProjectID"];
Note that I am setting the Response cookie in all the forms after I read the Request cookie. Is this necessary? Do the Request cookies copy to the Response automatically?
I'm setting no properties on the cookies and create them this way:
Response.Cookies["currentForm"]["selectedProjectID"] = someGuid.ToString();
The intention is that these are temporary header cookies, not persisted on the client any longer than the browser session. I ask this since I don't often write websites.
Before changing any code, I would investigate why session variables are disappearing.
Perhaps it is as simple as changing the timeout setting in the web.config?
Here's a list of the session state settings in the config file: Session Element on MSDN
====================================================
Oh yeah, one other thing to try in relation to your comment:
If my memory serves me, we had some issues in the past when deploying to a web garden/farm where multiple web sites on the same server would "clash". To get round this we explicitly names the cookie as so:
<authentication mode="Forms" >
<forms loginUrl="your-login-page.aspx"
cookieless="AutoDetect"
name=".A-NAME-WHICH-IS-UNIQUE" />
</authentication>
Name: Optional attribute.
Specifies the HTTP cookie to use for authentication. If multiple applications are running on a single server and each application requires a unique cookie, you must configure the cookie name in each Web.config file for each application.
The default is ".ASPXAUTH".
From here link text
No you do not have to keep resetting the cookie in the response.
Once set that cookie will continue to be sent with each subsquent request.
However I agree with Dominic you should first determine the reason you are unable to maintain the session in the first place.
Some reasons are:-
The host is using a web garden or a load balancer that does not support session affiliation
There is an aggressive setting for session timeout on the host
The host has a problem and is recycling the application pool frequently
Your client has overly tight cookie settings and is rejecting all cookies (however that would mean your alternative solution wouldn't work either)
Application logic may be faulty causing Session.Abandon or Session.Clear when it ought not.
In answer to your question about copying the cookie from the request to the response, no this is not necessary.
When the cookie is created it can persist for as long as you require.
If it is just needed for the duration of the session then do not set anything against the Expires property. In this case the cookie will be held in the browser memory and served up with each request to you website until the browser is closed.
If it is to persist between sessions the set the appropriate DateTime value against the Expires property. In this case the cookie is written as a file on the client machine and continue to be served up with each request to your website until it's exiry date is reached or it is deleted.
Of course, be aware clients can disble cookies in their browser.
I do agree with previous answer, that you should investigate the sessions timing out first!
But regarding cookies:
Request cookies are the cookies sent from the client to the server and Response cookies are the ones sent from server, telling the client to save them locally and attach them to the next, and all upcoming until the cookie is outdated, requests to the server.
Cookies have a limit on size and because of their behavior will create an overhead on data sent between server and client on requests, and can of course also be disabled on client side as well.
I would suspect that the reason you might be loosing session variables is that your application is running in a web garden. This means two or more processes are running your application.
In your web.config there should be sessionState tag. If mode="InProc" then try setting mode="StateServer". This will cause all the processeses hosting your application to use the session state server to store the session state elements. Also check the timeout as was mentioned previously.
The research I've done into cookies suggests they would not be a desirable alternative to session variables. Browsers enforce arbitrary limits on the number of cookies that can exist at any one time as well as the number per site. They are also prone to being dropped randomly.
You can enable cookieless sessions. There are some potential issues but it might work for your site.
I was a webhost4life customer up until two months ago, the issue I was experiencing was the application pool being recycled frequently - probably because the host had some kind of problem. In the end I moved to a VPS and never looked back (not a webhost4life VPS either).
For Sharing hosting the best approach is to use SQL Session State.
It's a little bit slower but much more reliable.
I had the same problems back in the days and my Memory Sessions were always getting erased, this happends because someone on the same hosting environment didn't know how to accomplish stings and IIS just reset the Application Pool, or it could even do by Auto Refresh the AppPool from the Hosting point of View (so no website will hang).
Since I started to use SQL State ... I just must say WOW!
you have total control in everything, even set the timeout (Memory Sessions are set by the machine config and no matter what you set in code or web config you will never override that setting)
and you gain something new, if you change the code, you users will not need to left the website to re.login again as they will continue from their existing session.
Setting it up it's fairly easy and you have a ton of examples on how to accomplish such behavior.
no matter what you do, DO NOT GO to cookies as they are not reliable!
You might consider using this little library:
http://www.codeproject.com/KB/aspnet/Univar.aspx
It can automatically switch to the session whenever the cookie is unavailable. It also has a server side implementation of the cookie whereby all cookies are stored on the server and asp.net authentification can be used to identify the user.