Search This Blog

Friday, August 10, 2012

Asp.net:secure web-service in Ajax 1.0



This article can be used for .net 1.0(Vs2003) to secure webservices which is called on aspx page throgh core AJAX like xmlhttp. in this article no .net ajax component is used but it can be used for .net2.5 and 3.0 2005 and 2008 with a little bit trick which I will give in my next post.
on aspx page.

you have set the header. and call the web service using get method.
hope this help 
if you find any difficulties  please post your comment.
xmlhttp.setRequestHeader('securityTicket' , SECURITY_TICKET );

on aspx.vb page

Private Sub GenerateSecurityTicket()
        Dim cacheKey As String = User.Identity.Name + ":securityTicket"
        Dim securityTicket As String = Guid.NewGuid().ToString()

        Cache(cacheKey) = securityTicket

        Dim script As String = "<script type=""text/javascript"">" + String.Format("SECURITY_TICKET = '{0}';", securityTicket) + "</script>"

        Page.RegisterClientScriptBlock("securityKey", script)
    End Sub

page_load()
GenerateSecurityTicket()
end sub


asmx Page

Private Sub EnsureTicket()
        Dim context As HttpContext = HttpContext.Current

        Dim headerTicket As String = context.Request.Headers("securityTicket")

        If headerTicket Is Nothing Or headerTicket = String.Empty Then
            Throw New System.Exception("Security ticket must be present.")
        End If

        Dim cacheKey As String = context.User.Identity.Name + ":securityTicket"
        Dim cacheTicket As String = DirectCast(context.Cache(cacheKey), String)

        If String.Compare(headerTicket, cacheTicket, False) <> 0 Then
            Throw New System.Exception("Security ticket mismatched.")
        End If
    End Sub


call EnsureTicket()

from every webmethod