Get session object from sessionID in ASP.Net - asp.net

Is there anyway to get a session object from a sessionID?
I have a small project using a Flash upload to let a user upload their file to the server, but the problem is that Flash has some error when sending the session and cookie (in Firefox or Chrome, but not IE), so I found a solution to fix this problem: sending the sessionID through Flash to the server, and on the server, decode sessionID back to the session object, but I don't how to do it. I'm using ASP.NET and C#.
Can anyone advise me on what to do?

The link proposed by Moo-Juice is no longer working.
I used the code provided in this page:
http://snipplr.com/view/15180/
It worked like a charm.
If the link would become broken, here is the code:
void Application_BeginRequest(object sender, EventArgs e)
{
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SESSIONID";
string session_value = Request.Form[session_param_name] ?? Request.QueryString[session_param_name];
if (session_value != null) { UpdateCookie(session_cookie_name, session_value); }
}
catch (Exception) { }
try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
string auth_value = Request.Form[auth_param_name] ?? Request.QueryString[auth_param_name];
if (auth_value != null) { UpdateCookie(auth_cookie_name, auth_value); }
}
catch (Exception) { }
}
void UpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (cookie == null)
{
HttpCookie cookie1 = new HttpCookie(cookie_name, cookie_value);
Response.Cookies.Add(cookie1);
}
else
{
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}
}

Related

Trying to prevent session tampering works on local environment but not on prod server

So i want to prevent session tampering in my site and i implemented this in global.asax. What im doing is im generating a hash key using the GenerateHashKey function. which basically uses the browser version,userhost address etc to create a hash key. This hash key im attaching to ASP.NET_SessionId cookie. Now this works perfectly in local environment. but as soon as i host it to prod server, the "Invalid" exception is thrown the first time and then it works fine. why is this happening
I used this article
http://www.codeproject.com/Articles/859579/Hack-proof-your-asp-net-applications-from-Session
protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
if (Request.Cookies["ASP.NET_SessionId"] != null && Request.Cookies["ASP.NET_SessionId"].Value != null)
{
string newSessionID = Request.Cookies["ASP.NET_SessionId"].Value;
//Check the valid length of your Generated Session ID
if (newSessionID.Length <= 24)
{
//Log the attack details here
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30);
Response.Cookies["ASP.NET_SessionId"].Value = null;
throw new HttpException("Empty");
}
//Genrate Hash key for this User,Browser and machine and match with the Entered NewSessionID
if (GenerateHashKey() != newSessionID.Substring(24))
{
//Log the attack details here
Response.Cookies["TriedTohack"].Value = "True";
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30);
Response.Cookies["ASP.NET_SessionId"].Value = null;
throw new HttpException("Invalid:"+newSessionID);
}
//Use the default one so application will work as usual//ASP.NET_SessionId
Request.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.Substring(0, 24);
}
}
catch(Exception Ex)
{
if (Ex.Message == "Invalid")
{
Response.Redirect(string.Format("~/PraiseError.aspx?Message={0}", Uri.EscapeDataString(Ex.Message)));
}
else
{
Response.Redirect("~/Home.aspx");
}
}
}
protected void Application_EndRequest(object sender, EventArgs e)
{
string gn = GenerateHashKey();
try
{
//Pass the custom Session ID to the browser.
if (Response.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.Replace(gn, "") + gn;
}
else
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + gn;
}
}
catch
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + gn;
}
}
private string GenerateHashKey()
{
StringBuilder myStr = new StringBuilder();
myStr.Append(Request.Browser.Browser);
myStr.Append(Request.Browser.Platform);
myStr.Append(Request.Browser.MajorVersion);
myStr.Append(Request.Browser.MinorVersion);
myStr.Append(Request.UserHostAddress);
//myStr.Append(Request.LogonUserIdentity.User.Value);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hashdata = sha.ComputeHash(Encoding.UTF8.GetBytes(myStr.ToString()));
return Convert.ToBase64String(hashdata);
}

How to compress asp.net page in code level?

I added a method called Application_PreRequestHandlerExecute in global.ascx like this:
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
string sExtentionOfThisFile = System.IO.Path.GetExtension(cTheFile);
if (sExtentionOfThisFile.Equals(".aspx", StringComparison.InvariantCultureIgnoreCase))
{
HttpApplication httpApp = (HttpApplication)sender;
string acceptEncoding = httpApp.Request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding))
{
return;
}
acceptEncoding = acceptEncoding.ToLower();
System.IO.Stream requestStream = httpApp.Response.Filter;
if (acceptEncoding.Contains("gzip"))
{
httpApp.Response.Filter = new System.IO.Compression.GZipStream(requestStream,
System.IO.Compression.CompressionMode.Compress);
httpApp.Response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
httpApp.Response.Filter = new System.IO.Compression.DeflateStream(requestStream,
System.IO.Compression.CompressionMode.Compress);
httpApp.Response.AppendHeader("Content-Encoding", "deflate");
}
}
}
It worked when browse normal page.
but if a page contains UPDATE-PANEL error will happen.
I get a PageRequestParserException.
when update-panel async post back, this error happens.
any idea?
I "fixed" by set the EnableEventValidation to false on my page and move compress logic to page's constructor.
Obviously this is not a good solution(close validation).
If anybody know a good solution, pls let me know.
and found that if the project's framework version is 3.5, all works fine,
but if the version is 2.0. this error will happen.

Using session for user authentication in asp.net c#

I am using session to authenticate a user. I have 2 web pages in my project. One is webform and other one is EntryForm.aspx and other one is log.aspx
In log.aspx i have done
protected void Button1_Click(object sender, EventArgs e)
{
user_login loginu = new user_login();
String uid_db = loginu.login(this.DropDownList1, this.TextBox1, this.TextBox2, this.Label5);
if (uid_db == "invalid")
{
Label5.Visible = true;
Label5.Text = "Invalid Login";
}
else
{
string uname = uid_db.Substring(0, uid_db.IndexOf(",")).Trim();
string[] tokens = uid_db.Split(',');
string dbname = tokens[tokens.Length - 1];
Session["login"] = uname;
Session["db"] = dbname;
Response.Redirect("EntryForm.aspx");
}
}
In class user_login I am taking the password stored in the database and matching it with the value entered by user. if it finds a value i redirect it to EntryForm.aspx. In which i check for session variable as follows
protected void Page_Load(object sender, EventArgs e)
{// CHEK SESSION VARIABLE AND LOAD dropdownlist1 WITH VALUES
if (!IsPostBack)
{
String DB = "";
String AccountID = "";
if (Session["login"] != null && Session["db"] != null)
{
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
}
else
{
Response.Redirect("log.aspx");
}
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
}
This is what i have done do authenticate a user. On server i have done the following configuration:
I have done no settings in Global.asax nor anything is web.config . I have seen many forum wherein Global.asax and web.config is configured.
I want to know what do i need to do in my project in order to be very efficient to work. I am facing problem with session timeout. I have set it to 20 mins on my server but sometimes suddenly i get logged out.
Please help me to understand using session for authentication.
First of all you have to edit web.config and set session timeout attribute.
<configuration>
<system.web>
<sessionState timeout="200"></sessionState>
</system.web>
</configuration>
Another issue is the use of IsPostBack block.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["login"] != null && Session["db"] != null)
{
String DB = "";
String AccountID = "";
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
else
{
Response.Redirect("log.aspx");
}
}

How to properly authenticate mvc-mini-profiler with AspNetSqlMembershipProvider

I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hit and Authenticate it's hit with some of the request and the profiler does not show up.
Checking only for Request.IsLocal works fine.
if(Request.IsAuthenticated)
{
if(User.IsInRole("Admin");
MiniProfiler.Start();
}
Any idea or why it's not working or better way to do it?
[Update] I accepted the awnser but undid it as I didn't quite get it do work
I did the following but the profiler is not showing up at first.
After a few tries it started showing up, even when I tried to acess the site with incognito mode, so no cookie.
protected void Application_PostAuthorizeRequest(Object sender, EventArgs e)
{
if (User.IsInRole("Admin"))
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if (cookie == null)
{
cookie = new HttpCookie("RoleProfiler");
cookie.Value = "yes";
cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
}
}
}
And I'm checking with
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if ((cookie != null) && (cookie.Value == "yes") )
{
MvcMiniProfiler.MiniProfiler.Start();
}
}
And ending at the end of the request.
protected void Application_EndRequest()
{
MvcMiniProfiler.MiniProfiler.Stop();
}
[Update2] Closing question, ignore this, I was being owned by outputcache.
The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:
protected void Application_BeginRequest()
{
MvcMiniProfiler.MiniProfiler.Start();
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(!CurrentUserIsAllowedToSeeProfiler())
{
MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}
}
Begin request happens before the user is fully authenticated in the request life cycle.
I solved this issue by adding a cookie if the user is in a role ("Admin" in your case) when the request is authenticated then you can check for this cookie on begin request and initialise the profiler.
It wont't work the first time but should every time after that.
This is my 2cent.
context.AcquireRequestState += (sender, e) =>
{
// Check debug in session. Can be set from Querystring. (?debug=true)
if (HttpContext.Current.Session != null && HttpContext.Current.Session["Debug"] != null)
{
try{
bool debug = (bool)HttpContext.Current.Session["Debug"];
if (debug == true)
MiniProfiler.Start();
else
MiniProfiler.Stop(discardResults: true);
}
catch{
MiniProfiler.Stop(discardResults: true);
}
}// Or always show if Administrator.
else if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
bool admin = HttpContext.Current.User.IsInRole("Administrator");
if (admin == false)
{
MiniProfiler.Stop(discardResults: true);
}
}
else
{
MiniProfiler.Stop(discardResults: true);
}
};

Infinite loop with HTTP 401 status

I wrote an ASP.NET page that requires HTTP Basic authorization, which I put in the Page_Load function:
void Page_Load(object sender, EventArgs e)
{
string auth = Request.Headers["Authorization"];
if (string.IsNullOrEmpty(auth))
{
Response.StatusCode = 401;
}
else
{
string[] usernameAndPassword = Encoding.UTF8.GetString(Convert.FromBase64String(auth)).Split(':');
string username = usernameAndPassword[0];
string password = usernameAndPassword[1];
Login(username, password);
}
}
When I try to view the page in a browser (either Firefox or IE), it asks me for the username and password, and then...asks me for the username and password again.
Why does this happen, and how can I fix it?
This should be handled though a httpmodule. Please consider following article.
http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx

Resources