开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜