ASP.NET HttpModule : detect first request in a session - asp.net

I have written a HttpModule for our site which generally accepts requests and checks for specific file extensions as well as the value of a specific session variable. Is it possible to detect the first request in a session?

There's a property on HttpSessionState you can use called IsNewSession, e.g.:
if(Context.Session != null && Context.Session.IsNewSession) {
//do something, session was created this request
}
You can only do this after session state is available of course, but from what you're doing in your module, that doesn't seem to be a problem, please comment if it is.

Related

Create session with BASIC authentication

I want to write a servlet with which I can create a new session.
The servlet requires the user to authenticate with BASIC authentication and returns the standard session cookie (using HttpServletRequest#getSession(true)). However, if the client uses the received session cookie in his next request instead of BASIC authentication it is not authenticated. The server recognizes the session but it doesn't contain the user information.
I'm using Tomcat and after a bit of debugging the reason is also obvious: the user information (Principal) is added to session upon authentication. However when the first BASIC authentication is taking place no session exists yet as this will be created by the servlet. Does anyone have idea how to solve this problem?
After one night of sleep [1] I believe I have come up with a working solution myself. The following snippet (using JAX-RS, but it shouldn't be too difficult to translate it to plain servlet code) does the trick if the calling client will follow redirects:
public Response getSessionCookie() {
boolean sessionExists = m_servletRequest.getSession(false) != null;
if (sessionExists) {
return Response.noContent().build();
} else {
HttpSession session = m_servletRequest.getSession();
return Response.status(Status.TEMPORARY_REDIRECT)
.header("Location",
m_uriInfo.getAbsolutePathBuilder().matrixParam("jsessionid", session.getId()).build())
.build();
}
}
The first request will create a session and redirect the client to the same address but with the session ID in the URL (which is important). The client will follow the request and send the same BASIC authentication data again but now it will be registered in the existing session. The second invocation of the method above will simply return an empty response with the session cookie that can now be used for subsequent requests.
Note that the session cookie is different for me in the second response but looking at Tomcat code this seems to be deliberate (successful authentication will always create a new session).
[1] Sleep is highly underestimated!

Nhibernate with Asp.net WebForms - Session per Request

I am using an HttpModule to open a session that span each request and it works great with lazy loading and everything.
My concern is that since I open a new session per request (and stores it in HttpContext.Current.Items) it opens a session for every request even request including request for .css files and images.
I recall reading that session creation is a pretty lightwheigt operation (dont know about transactions though) but anyway it seems unnecessary to open a session for a requests for a .css file?
Anyone got some ideas about this, is it a problem and/or am I doing something stupid?
Thanks in advance
only create the session object if the file type is .aspx or .ashx:
switch (context.Request.CurrentExecutionFilePathExtension.ToLower())
{
case ".aspx":
case ".ashx":
context.Items[ContextKey] = CreateMySession();
break;
}
or encapsulate session creation inside a property getter, and clean-up checks whether session != null

Conditional output caching in ASP.NET

I have a question on how to programmatically instruct ASP.NET to skip resolving a request from the output cache.
Imagine you've got a page output cached (e.g. http://domain/page.aspx) by means of applying cache policy settings from a CMS to the HttpResponse at runtime. On a per request basis depending on i.e. the current user is authenticated + a member of a set of known groups (or matched by business logic), I would like to instruct ASP.NET to skip resolving a request from the output cache.
The scenario is that two different users are on the system at the same time (or more). User A is authenticated + a member of a set of known groups, and user B is anonymous. Regardless of the page being output cached, I want the authenticated user to browse all pages as if no output caching was enabled - ever; at the same time, I would like ASP.NET to continue serving output cached pages to anonymous users (or, users who isn't matched by business logic).
The typical suggestion is to use VaryByHeader, VaryByParam etc. and pollute the output cache - not good, but while digging in the output cache module using Reflector, I noticed that the output cache module skips the current request in case a couple of known "cache-control" headers are present. As far as I'm concerned about headers, these are sent from the browser if the user forces a fresh copy to be rendered by hitting F5 or ENTER in the address bar.
So, what I'm doing is simply setting the "cache-control" header to "no-cache" in a custom http module in an event that goes before the ResolveRequestCache event to which the output cache subscribes. Like this:
context.Request.Headers["Cache-Control"] = "no-cache";
All is nice and dandy, however, if the HttpCachePolicy.SetValidUntilExpires(true) cache policy is set, ASP.NET disregards the request header previously set and serves the request from the output cache.
As an alternative, I guess I could write additional code in a post-processing event in the same http module to ensure that HttpCachePolicy.SetValidUntilExpires(false) is called, in case output caching has been configured, but I think it would be a more clean solution to actually be able to instruct ASP.NET to simply skip resolving the request from the output cache. I can imagine a lot of ackward solutions to this question, but I'm after the right one.
For reference, I have been trying most if not all relevant methods of the HttpCachePolicy class e.g.:
HttpResponse.Cache.SetNoServerCaching()).
You can add an HttpCacheValidateHandler to your application in which you can implement any logic you want. It will be executed during the ResolveRequestCache event which is fired after Authentication and Authorization have been executed. The key is to return HttpValidationStatus.IgnoreThisRequest in the case where you want to bypass the Cache.
See this sample HttpModule for reference:
public class CacheModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest +=
(s, e) => context.Context.Response.Cache
.AddValidationCallback(CacheHandler, null);
}
private static void CacheHandler(
HttpContext context, object data,
ref HttpValidationStatus validationstatus)
{
// bypass cache for all users with skipCache cookie
validationstatus =
context.Request.Cookies["skipCache"] != null
? HttpValidationStatus.IgnoreThisRequest
: HttpValidationStatus.Valid;
}
public void Dispose()
{
}
}
I'm not sure whether there is a supported method of doing this after something is cached.
But why don't you like the VaryByHeader option? Assuming there is a header you can look at to differentiate between logged in and not logged in users, that should work. It wouldn't pollute the cache if you have logic to only populate the output cache if the user is not logged in. Logged in users would alway get cache misses.

ASP.NET: Session.SessionID changes between requests

Why does the property SessionID on the Session-object in an ASP.NET-page change between requests?
I have a page like this:
...
<div>
SessionID: <%= SessionID %>
</div>
...
And the output keeps changing every time I hit F5, independent of browser.
This is the reason
When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.sessionid.aspx
So basically, unless you access your session object on the backend, a new sessionId will be generated with each request
EDIT
This code must be added on the file Global.asax. It adds an entry to the Session object so you fix the session until it expires.
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
}
There is another, more insidious reason, why this may occur even when the Session object has been initialized as demonstrated by Cladudio.
In the Web.config, if there is an <httpCookies> entry that is set to requireSSL="true" but you are not actually using HTTPS: for a specific request, then the session cookie is not sent (or maybe not returned, I'm not sure which) which means that you end up with a brand new session for each request.
I found this one the hard way, spending several hours going back and forth between several commits in my source control, until I found what specific change had broken my application.
In my case I figured out that the session cookie had a domain that included www. prefix, while I was requesting page with no www..
Adding www. to the URL immediately fixed the problem. Later I changed cookie's domain to be set to .mysite.com instead of www.mysite.com.
my problem was that we had this set in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true" />
this means that when debugging in non-SSL (the default), the auth cookie would not get sent back to the server. this would mean that the server would send a new auth cookie (with a new session) for every request back to the client.
the fix is to either set requiressl to false in web.config and true in web.release.config or turn on SSL while debugging:
Using Neville's answer (deleting requireSSL = true, in web.config) and slightly modifying Joel Etherton's code, here is the code that should handle a site that runs in both SSL mode and non SSL mode, depending on the user and the page (I am jumping back into code and haven't tested it on SSL yet, but expect it should work - will be too busy later to get back to this, so here it is:
if (HttpContext.Current.Response.Cookies.Count > 0)
{
foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
{
HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
}
}
}
Another possibility that causes the SessionID to change between requests, even when Session_OnStart is defined and/or a Session has been initialized, is that the URL hostname contains an invalid character (such as an underscore). I believe this is IE specific (not verified), but if your URL is, say, http://server_name/app, then IE will block all cookies and your session information will not be accessible between requests.
In fact, each request will spin up a separate session on the server, so if your page contains multiple images, script tags, etc., then each of those GET requests will result in a different session on the server.
Further information: http://support.microsoft.com/kb/316112
My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue
<sessionState cookieless="true" />
Here's a REALLY old article about it:
Cookieless ASP.NET
in my case it was because I was modifying session after redirecting from a gateway in an external application, so because I was using IP instead on localhost in that page url it was actually considered different website with different sessions.
In summary
pay more attention if you are debugging a hosted application on IIS instead of IIS express and mixing your machine http://Ip and http://localhost in various pages
In my case this was happening a lot in my development and test environments. After trying all of the above solutions without any success I found that I was able to fix this problem by deleting all session cookies. The web developer extension makes this very easy to do. I mostly use Firefox for testing and development, but this also happened while testing in Chrome. The fix also worked in Chrome.
I haven't had to do this yet in the production environment and have not received any reports of people not being able to log in. This also only seemed to happen after making the session cookies to be secure. It never happened in the past when they were not secure.
Update: this only started happening after we changed the session cookie to make it secure. I've determined that the exact issue was caused by there being two or more session cookies in the browser with the same path and domain. The one that was always the problem was the one that had an empty or null value. After deleting that particular cookie the issue was resolved. I've also added code in Global.asax.cs Sessin_Start method to check for this empty cookie and if so set it's expiration date to something in the past.
HttpCookieCollection cookies = Response.Cookies;
for (int i = 0; i < cookies.Count; i++)
{
HttpCookie cookie = cookies.Get(i);
if (cookie != null)
{
if ((cookie.Name == "ASP.NET_SessionId" || cookie.Name == "ASP.NET_SessionID") && String.IsNullOrEmpty(cookie.Value))
{
//Try resetting the expiration date of the session cookie to something in the past and/or deleting it.
//Reset the expiration time of the cookie to one hour, one minute and one second in the past
if (Response.Cookies[cookie.Name] != null)
Response.Cookies[cookie.Name].Expires = DateTime.Today.Subtract(new TimeSpan(1, 1, 1));
}
}
}
This was changing for me beginning with .NET 4.7.2 and it was due to the SameSite property on the session cookie. See here for more info: https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
The default value changed to "Lax" and started breaking things. I changed it to "None" and things worked as expected.
Be sure that you do not have a session timeout that is very short, and also make sure that if you are using cookie based sessions that you are accepting the session.
The FireFox webDeveloperToolbar is helpful at times like this as you can see the cookies set for your application.
Session ID resetting may have many causes. However any mentioned above doesn't relate to my problem. So I'll describe it for future reference.
In my case a new session created on each request resulted in infinite redirect loop. The redirect action takes place in OnActionExecuting event.
Also I've been clearing all http headers (also in OnActionExecuting event using Response.ClearHeaders method) in order to prevent caching sites on client side. But that method clears all headers including informations about user's session, and consequently all data in Temp storage (which I was using later in program). So even setting new session in Session_Start event didn't help.
To resolve my problem I ensured not to remove the headers when a redirection occurs.
Hope it helps someone.
I ran into this issue a different way. The controllers that had this attribute [SessionState(SessionStateBehavior.ReadOnly)] were reading from a different session even though I had set a value in the original session upon app startup. I was adding the session value via the _layout.cshtml (maybe not the best idea?)
It was clearly the ReadOnly causing the issue because when I removed the attribute, the original session (and SessionId) would stay in tact. Using Claudio's/Microsoft's solution fixed it.
I'm on .NET Core 2.1 and I'm well aware that the question isn't about Core. Yet the internet is lacking and Google brought me here so hoping to save someone a few hours.
Startup.cs
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder
.WithOrigins("http://localhost:3000") // important
.AllowCredentials() // important
.AllowAnyMethod()
.AllowAnyHeader(); // obviously just for testing
}));
client.js
const resp = await fetch("https://localhost:5001/api/user", {
method: 'POST',
credentials: 'include', // important
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
Controllers/LoginController.cs
namespace WebServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IEnumerable<string> Post([FromBody]LoginForm lf)
{
string prevUsername = HttpContext.Session.GetString("username");
Console.WriteLine("Previous username: " + prevUsername);
HttpContext.Session.SetString("username", lf.username);
return new string[] { lf.username, lf.password };
}
}
}
Notice that the session writing and reading works, yet no cookies seem to be passed to the browser. At least I couldn't find a "Set-Cookie" header anywhere.

How to detect session timeouts when using cookieless sessions

I'm currently working on a ASP.Net 3.5 project and trying to implement session timeout detection. I know how to do it with enabled session cookies, but without i'm totally lost.
When session timeout occurs i want to redirect the user to some custom page.
Can someone explain me how to do it?
My cookie based solution looks like this and i wan't to reproduce its behaviour:
if (Session.IsNewSession && (Request.Cookies["ASP.NET_SessionId"] != null))
Response.Redirect("...");
Session_End in the global.asax should always be fired, despite the type of session used.
-edit: you might also be interested in
Session.IsNewSession
as this gives you information on new requests whether the previous session could have been timed out.
It looks like i've found a solution. I'm not very happy with it, but for the moment it works.
I've added a hidden field to my page markup
<asp:HiddenField ID="sessionID" runat="server" />
and following code to my CodeBehind
public void Page_Load(object sender, EventArgs eventArgs)
{
if (Context.Session != null) {
if (Context.Session.IsNewSession) {
if (!string.IsNullOrEmpty(sessionID.Value)) {
Response.Redirect("~/Timeout.aspx")
}
}
sessionID.Value = Context.Session.SessionID;
}
}
You also need to add this to your Web.config or ASP ignores all posted form fields
<sessionState cookieless="true" regenerateExpiredSessionId="false"/>
regenerateExpiredSessionId is the important attribute.
It pretty much works the same way - the session service updates a timestamp every time ASP.NET receives a request with that session ID in the URL. When the current time is > n over the timestamp, the session expires.
If you put something in session and check to see if it's there on each request, if it is not, you know the session is fresh (replacing an expired one or a new user).
I'd take a look at the "Database" section of AnthonyWJones' answer to a similar question here:
ASP.Net Session Timeout detection: Is Session.IsNewSession and SessionCookie detection the best way to do this?
In your session start event, you should be able to check a database for the existence of the SessionID - I assume that if I request a page with the SessionID in the URL, then that is the SessionID that I'll use - I've not tested that.
You should make sure you clear this DB down when a user logs out manually to ensure that you store a new instance of your flag.
If you don't like Session_End, you can try a very quick and dirty solution. Set up a Session["Foo"] value in Session_Start in global.asax, then check for Session["Foo"] in your page. If is null, the session is expired..
This is one of the solutions proposed in the Nikhil's Blog. Check it.

Resources