Dealing with an empty Session in asp.net - asp.net

I have a question about empty session and "try-catch" handling.
I have few forms that use a session to pass data one to each other and sometime when the user is stay for a long time on specific page he cannot continue to the next page because the session is empty.
I want to handle it somehow but i have no idea.

On page load of the next page, check if the user has valid session, if not then redirect to the login page.
Suppose you store user's login id in LoginID field of the session, then you can check as following
if(Session["LoginID"]==null || Convert.ToString(Session["LoginID"])==string.Empty)
{
//Redirect to login page
}

Session is a collection.
You can use its Count property.
if(Session.Count == 0)
{
// session is empty
}

Related

Saving QueryString to protect URL manipulation

Is there a way to save the querystring ids after the page load? the reason why i am looking is that ...i should be back and forth with pages and more importantly if the user try to manupluate the ids then it should not effect the result of my page since i will be reading the Ids not from querystring but from some save prop or something like that.
for an example: let says the page loads very first time... i have this url:
http://www.somesite.com/Shop/Product/Detail.aspx?ProductId=100
and if the user try to modify the querystirng and re-load the page then the page_load should not read from querystring rather from saved prop or something???
In your page load event look at the Page.IsPostBack property. It is false when a page is first loaded. You should validate your parameters then and perhaps save them to session or viewstate.
If Page.IsPostback = false Then
'Validate Request("ProductID") here
'Save in viewstate or session state
Else
'Retrieve ProductID from viewstate or session state
End If
If a user changes the query string, you should consider it a new page load.
This would not work since it's against the very basic nature of Internet. Internet is stateless.
Everytime user changes the querystring, it will be treated as a new Url, storing the parameters will be of no use. Page.IsPostback won't work either since every Url change will be a first hit.
Saying that, you can still work around it,
With every Url, you can pass a unique identifier (like a GUID.)
As soon as page hits, you can save parameters in session and work with them and use the Guid to map the two requests.
But the problem remains here, if the user changes that Guid then again it will be treated as a new request. You can go one step ahead and start saving that GUID to make sure that only system generated GUIDs are handled but overall it will just make your system complex.
My guess is that you might be looking at a wrong solution for your problem. If you can share your actual aim then we might be able to recommend you something more tangible.
You can not stop users from editing querystring values and trying to see content of another page or execute something. what you can do is you can check in the page load that this user has sufficient permission to access this page.
Ex : www.mysite.com/editproduct.aspx?productid=4
In editproduct.aspx, you have to check whether the product 4 has access by the current user who is accessing the page.( May he should be the creator/ he should be in a specific power users group etc... depending upon your scenario). If he has access, show the edit form to the user, else hide it and show a message saying "you are not authorized to access this resource."
There is no way; however, you can use session to validate when the Page_load is called.
If ( Page.isPostBack = true ) {
Session("SAVE") = false;
}
For a while in the before the Request.Querystring statement, you validate the 'save' session state.

ASP.NET session key for web service security?

I've got a web service (ASP.NET 2.0) that I'm calling from javascript using jQuery's $.ajax(). I've been told that the session key is often used as a nonce in a situation like this for security purposes; the web service takes a key as one of its parameters and only returns data if it matches the current session key.
I'm attempting to accomplish this by setting the value of a hidden field to the current SessionID on every Page_Load (i.e. every postback), then grabbing it in the javascript to pass as a parameter. But it's never the same key as the web service's current key (Context.Session.SessionID).
Is this possible to resolve, or should I be doing this another way?
EDIT: code to set session in hidden field as requested.
hfSession.Value = Context.Session.SessionID;
That's in the Page_Load of a .ascx control, not under any conditional (i.e. not wrapped with if (!Page.IsPostBack).
I believe you are trying to prevent Cross Site Script Request Forgery (CSRF). The Session ID is actually sent across as a cookie and the attacker can set this. Rather than use the Session ID itself, you should use a randomly generated number stored in a Session variable.
String GetCSRFToken()
{
String token = (String)Session["CSRFToken"];
if( token == null )
{
token = GenerateLongRandomString();
Session["CSRFToken"] = token;
}
return token;
}
void AssertValidCSRFToken(String token)
{
if( token != GetCSRFToken() )
{
throw new Exception("Invalid Request!")
}
}
Here is a link to another question with more info on preventing this kind of attack:
CSRF Validation Token: session id safe?
Asp.net actually generates a new Session ID for every request until you use the Session State to store some value. This could be a reason why the values are different. Try and save something in the session. Perhaps
Session["SessionID"] = Context.Session.SessionID;
hfSession.Value = Context.Session.SessionID;
A new SessionID is generated each time the page loads until the session is actually allocated. So if you don't actually allocate anything to the session, the SessionID will change upon each page load.

How to implement login session in asp.net and C#

I'm new to asp.net and C# and I want to ask how to implement a session login using asp.net and C#.
Please advise.
Thanks.
In C# you can define a session variable like this:
Session["userame"]= txtusername.Text;
where txtusername is a text box. In another page you can call it as:
string usrname = Session["username"].ToString();
To check whether a user is logged in or not, in a particular page; you'll have to check if this session is empty or not. If the session is null then redirect the user to login page else he/she can view the page. Same logic applies to all the pages where you want to implement the session validation. Sample (on Page_Load event):
if (Session["username"] == null)
Response.Redirect ("Login.aspx");
Hope it helps... :)
The question is broad answer, in Simply you can follow like this
Create database, user table in sql server or any database of your choice
Create the login form with userid and password
Check them with database for user availability
If User exist and password matches create a session, like Session.Add ("Userid", txtUserid.Text);
In other pages (restricted pages where only registered users allowed) write this code in every page load event
if (Session["Userid"] == null)
Response.Redirect ("Login.aspx");
Session["login_user"] = "[username]";
string username = Session["login_user"].ToString().Trim();
Easiest way to implement session is as following:
Session["SessionName"] = Value;
For retrieving value
String variable = Session["SessionName"].ToString();
Note: Session variable can be of any type.
Generally session is used for checking whether the user is logged in or not.

Preventing Re-submission of data on Browser Refresh

I have a form. On submit of a button, it inserts a record into the db. If I go back in my browser and refresh the page it's resubmitting it causing all sorts of issues as you can imagine. How do I ensure that the user can't refresh the previous page and the state of that page does another automatic submit on refresh like this?
I'm not using ViewState. I actually have it disabled in the page directive
No, Response.Redirect does NOT solve this problem. The user can still go back with the browser's back button and refresh at the point where they submitted and it will still run the button's event sending the data downstream to my DL insert
The solution I use most often is this:
When the user first visits the page (Non-PostBack), generate a token value (GUID is easy). Take this token value and store it in their Session variables and a hidden field in the page. Being a field, this value should persist through round trips to the server without ViewState enabled (I could be mistaken on that count, so please check it!). Should the page be refreshed (and form values lost), a new value will be generated by the Non-PostBack initialization.
When the page is posted back, retrieve the hidden field value and compare it against the expected value in the user's Session variables:
If the tokens match, accept the submission as "genuine", remove the token from the Session variables, and continue your workflow.
If the token is missing from Session variables, the user is trying to submit the form again. - If the tokens do not match, the user is "replaying" an old submission of the form.
Example code to achieve this sort of solution:
public partial class MyPage : Page
{
protected HiddenField tokenField;
protected void Page_Load()
{
if(!IsPostBack)
CreateToken();
}
// Call this method to establish a token in session and on the page.
private void CreateToken()
{
string token = new Guid().ToString();
Session["dupeToken"] = token;
tokenField.Value = token;
}
// Call this method to validate the token before continuing workflow.
private bool TokenIsValid()
{
string expectedToken = (string)Session["dupeToken"];
if(expectedToken == null)
return false;
string actualToken = tokenField.Value;
return expectedToken == actualToken;
}
// Call this method when the page submission is complete to prevent re-submission.
private void ConsumeToken()
{
Session["dupeToken"] = null;
}
}
The easiest way would be to wrap the form in an < asp:UpdatePanel>. That way, all postbacks are done via AJAX and the browser will never ask you to re-submit your form.
The best two ways of doing this are:
Performing a check on a distinct field against the database
Create a hidden token in the form that uses a salt based on time. If you put logic in script to check for the existing time and compare it to the token, you can either allow the submission or define it. For example, if the form is drawn at a certain time, you store the token, and within 30-60 seconds you can submit, but after that you cannot.

ASP.NET: How to redirect, prefilling form data?

i want a handler to redirect to a web-forms page, pre-filling in the values of some controls on the form.
i tried setting my current Request.Form data:
if (theyWantToDoSomething)
{
//pre-fill form values
context.Request.Form["TextBox1"] = "test";
context.Request.Form["ComboBox1"] = "test 2";
context.Request.Form["TextBox2"] = GetTheTextForTheThing();
//tell the client to go there
context.Response.Redirect("~/SomeWebForm.aspx");
return;
}
But i get an exception that Form values are read only.
What would be a way to send the client to another page, pre-filling form data?
Answer
i used the Session state to store values. It's important to note that by default a Handler doesn't have access to Session (the Session object will be null). You have to tell IIS to give you the Session object by adding the IRequiresSessionState marker interface to your handler class:
public class Handler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
...
if (theyWantToDoSomething)
{
//pre-fill form values
context.Session["thing1"] = "test";
context.Session["thing2"] = "test 2";
context.Session["thing3"] = GetTheTextForTheThing();
//tell the client to go there
context.Response.Redirect("~/SomeWebForm.aspx");
return; //not strictly needed, since Redirect ends processing
}
...
}
}
You can only populate your Response, the Request is input data and is indeed read-only.
If you are using ASP.NET, there are a variety of ways you could accomplish what you need:
The best way would probably be to pass the data you need to be pre-populated to SomeWebForm.aspx via the Session object, and on that pages Load method, populate your form. Keep in mind that when you do Response.Redirect, a 302 response is sent to the client with the URL the client should redirect to. The process is transparent to the user...but there is a full round trip involved.
Another alternative to populating the users Session would be to add GET parameters via a query string to the redirect to SomeWebForm.aspx.
If you need to transfer processing to the SomeWebForm.aspx page without round tripping, you could use Server.Transfer. This will transfer execution from the current page to the page you choose...however, this can cause some odd behavior on the client end because the URL does not update. As far as the user is concerned, it will still appear as though they are on the same page they started on.
A few ideas that might get you started:
Pass the values in the query string
Store the values in the session state or in a seperate cookie
Store the values in HttpContext.Items and use Server.Transfer instead of Response.Redirect
Another approach that hasn't been mentioned yet is using Server.Transfer makes it possible to use the Page.PreviousPage property, allowing access to the controls on the page that transferred control.
As jrista mentioned though, using Transfer doesn't update the URL shown to the user, which may or may not be an issue. For example, a user can't precisely bookmark a page they got transferred to since the URL will be that of the original transferring page.

Resources