Secured ASP.Net Ajax call from javascript

I have a login page that on success set a Session variable:
Session("Username") = "jhon"

Open in new window

In that way I know that this user was authenticated.
If I use System.Web.UI.WebControls then the Session value exists and can be used.
but what if I want to call from javascript code?
If I use JQuery I must call a static function, like this:
$.ajax({ url: "mypage.aspx/myfunction", data: "…" + '<%=Session("Username") %>' + "'}", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8" });

Public Shared Sub myfunction(…)

Open in new window

How can I safely call?
p.s. I suppose I can do it with a Hidden Button in an UpdatePanel:
function doUpdate()
  document.getElementById("<%#= btnUpdate.ClientID %>").click();

Open in new window

... with additional HiddenField to store that data...
But is there a more elegant/correct way to do it?
Thanks, Aryeh.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
All requests from a browser return the cookies including Session cookies.  That means not only HTML pages but images, CSS, and JavaScript requests also.  So if your target page for your AJAX request is session aware, then you do not need to include the ID in the request.  You can merely get it from the session variable.
tuchfeldAuthor Commented:
I get this error:
Error	48	Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.

Open in new window

Dave BaldwinFixer of ProblemsCommented:
Someone else will have to help you with that.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Julian HansenCommented:
Can you explain what is you are trying to do - what is the purpose of checking the session by AJAX?
Surely if you have got as far as rendering the page then the state of the session variable is known. Are you checking if the session is still active?

With respect to your error - can you post some code that shows where you are getting that error.
tuchfeldAuthor Commented:
Let's look at this scenario:
User "george" has signed in.
and then "hack" and call like this:
$.ajax({ url: "mypage.aspx/myfunction", data: "{... 'john' ... other_data ...}", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8" });

Open in new window

i.e He can change John's data!
I do not want to allow this but only validate for the user that his name is in the session
Session("Username") = "John".
I suppose that doing so with the UpdatePanel environment is much more secured.
Julian HansenCommented:
Why would he be able to "hack" John's data.

Any request originating from the browser is checked server side - so any data coming in that is not expected can be rejected.

The way you are trying to do it is exactly the scenario where data can be hacked - by putting the session name into the AJAX call - it can be changed.

Nothing from the browser can ever be trusted - you have to assume that data coming in is dirty and make sure it is sanitized and validated on the server before you try and use it.

Hence my question about what you are trying to do? From your code you appear to be controlling session state from the browser which is not the right way to do it.
tuchfeldAuthor Commented:
Thanks for your effort. Let me try to explain again:
George (the hacker) has also logged-in (with user+password) to the Server.
So I think He is able to send requests to the server using JQuery Ajax and impersonate to John (as I wrote above).
As I said at the beginning:
As far as I understand: a "trusted" way to call the Server in ASP.Net
is using the UpdatePanel (see above).
Am I right?
If so, My Question is how to do this with JQuery Ajax
which as far as I know use a "simple" request - without Session values (Which I suppose are used for the validations) and therefore it can be hacked.
Is my description understood/correct? what is the solution?
Julian HansenCommented:
So I think He is able to send requests to the server using JQuery Ajax and impersonate to John (as I wrote above).
How is he going to impersonate John? If you are handling security properly on the backend then he won't be able to.

When you "authenticate" a user on the backend typically you setup a session for the user which is linked to a cookie that is placed on the users computer. When the user interacts with the server this cookie is passed backwards and forwards and is the primary means of checking which account the session is linked to.
George can come along and make impersonating calls (as John) back to the server but unless he has John's cookie his calls should be ignored because the session data linked to George's session does not match John's account.

An update panel is just an AJAX request back to the server - hence my question as to what you are trying to achieve.
tuchfeldAuthor Commented:
Here is the answer I was looking for:
<WebMethod(EnableSession:=True)> _
Public Shared Sub myfunction()
  Dim u = HttpContext.Current.Session("Username")
Accessing Session from Javascript using JQuery, AJAX in ASP.Net

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Dave BaldwinFixer of ProblemsCommented:
I would never do that.  I use AJAX with sessions all the time but I use PHP and not ASP.NET which is why I didn't try to give you a more detailed answer.  And I never put the user id in the AJAX code.
tuchfeldAuthor Commented:
I indicated specifically that I program in .Net environment.
Dave BaldwinFixer of ProblemsCommented:
Yes, you did, but sessions work basically the same in both languages.
Julian HansenCommented:
Here is the answer I was looking for:
Good luck with it - if you are trying to secure your site and you are going to be relying on the integrity of AJAX calls you are going to need it.
tuchfeldAuthor Commented:
Eventually it was me who found the solution.
But still I appreciate the assistance of the participants.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.