Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Session ID as a Parameter in an Ajax Call

I have created an HttpHandler that I will be using with a jquery-Ajax call.

This HttpHandler will access the database and check something related to the currently singed in user.

The user is considered signed in by using the Session, with an attribute called user_id.

Session["user_id"] = userId;

I tried to retrieve this Session in the HttpHandler but that doesn't seem to work.

So I thought about sending the user_id as a parameter.

    var user_id = //Retrieved in some way...
    $.ajax({
        url: 'QuestionRate.ashx?id=user_id',
        success: function (msg, status, xhr) {
            alert(msg);
        },
        error: function () {
            alert(msg);
        }
    });

But this really seems like a bad idea, anyone who will read the codes can simply access the Handler with the id that he wants.

So what can I do in this situation? I want the Handler to get the user_id for database access, yet I wanna make sure that this user_id is the actual id of the signed in user. There's no way to access the Session in the Handler?

like image 847
user1665700 Avatar asked Jan 14 '23 15:01

user1665700


2 Answers

Passing session id with an ajax call doesn't sound good.

You should mark your handler with the marker IReadOnlySessionState interface and access to session as read-only via HttpContext.Current.Session instance.


Code sample:

public class FooHandler : IHttpHandler, IReadOnlySessionState 
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        string user_id = context.Session["user_id"].ToString();
    }
}
like image 140
Yiğit Yener Avatar answered Jan 18 '23 22:01

Yiğit Yener


Make your handler implement IRequiresSessionState, that will notify ASP.NET that your handler uses Session state. Then the session cookie sent from the client will be recognized by the handler and you can access it on serverside as in any other aspx page for example.

Also you can use IReadOnlySessionState for read-only Session access.

like image 32
Honza Brestan Avatar answered Jan 19 '23 00:01

Honza Brestan