Ensuring the safety of JavaScript requests made to a Web Service

In my project, there is a page that triggers a JSon script when a button is clicked. This script interacts with a web service. To ensure security, the code behind the page generates a script containing an object with a unique code. This code is then added to the header of the page. However, the web service fails to verify this code as it cannot find the specified header (in other words, the header does not exist).

The following code snippet generates the code and JavaScript object (in .cs file):

    string cacheKey = User.Identity.Name + ":securityTicket";
    string securityTicket = Guid.NewGuid().ToString();

    Cache[cacheKey] = securityTicket;

    string script = string.Format("SECURITY_TICKET = '{0}';", securityTicket);

    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "securityKey", script, true);

This script adds the header (in .aspx file)

    function onInvoke(sender, args) {
        args.get_webRequest().get_headers()['securityTicket'] = SECURITY_TICKET;);
    }

The backend code for the web service (asmx.cs or similar): HttpContext context = HttpContext.Current;

        string headerTicket = context.Request.Headers["securityTicket"];

        if (string.IsNullOrEmpty(headerTicket))
        {
            throw new SecurityException("Security ticket must be present.");
        }

        string cacheKey = context.User.Identity.Name + ":securityTicket";
        string cacheTicket = (string)context.Cache[cacheKey];

        if (string.Compare(headerTicket, cacheTicket, false) != 0)
        {
            throw new SecurityException("Security ticket mismatched.");
        }

The issue arises when context.Request.Headers["securityTicket"] returns null.

Any insights or suggestions would be greatly appreciated. Thank you!

UPDATE:

The Web service:

namespace PV
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService()]
    public class UserService : System.Web.Services.WebService
    {
        [WebMethod]
        public bool ChangeUserPassword(object userID, object password)
        {
            EnsureTicket();
            return PV.WebMethods.ChangeUserPassword(userID, password);
        }

        private void EnsureTicket()
        {
            HttpContext context = HttpContext.Current;

            string headerTicket = context.Request.Headers["securityTicket"];

            if (string.IsNullOrEmpty(headerTicket))
            {
                throw new SecurityException("Security ticket must be present.");
            }

            string cacheKey = context.User.Identity.Name + ":securityTicket";
            string cacheTicket = (string)context.Cache[cacheKey];

            if (string.Compare(headerTicket, cacheTicket, false) != 0)
            {
                throw new SecurityException("Security ticket mismatched.");
            }
        }
    }
}

The Page:

    <script type="text/javascript" language="javascript">
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(beginRequest);
    function beginRequest(sender, args) {
        prm._scrollPosition = null;
        postbackElement = args.get_postBackElement();
    }
    var postbackElement;
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);

    function pageLoaded() {
        Sys.Net.WebRequestManager.add_invokingRequest(onInvoke);
        if (typeof (postbackElement) === "undefined") {
            return;
        }
        if ((postbackElement.id).indexOf("btnSelect") !== -1) {
            $("html, body").animate({ scrollTop: "300px" });
        }
    }

    function ApplicationLoadHandler() {
        // InitScript is a custom function 
        // registered from the User Control
        if (typeof InitScript == 'function')
            InitScript();
    }

    if (Sys && Sys.Application) {
        Sys.Application.add_load(ApplicationLoadHandler);
        Sys.Application.notifyScriptLoaded();
    }

    function pageUnload() {
        Sys.Net.WebRequestManager.remove_invokingRequest(onInvoke);
    }

    function onInvoke(sender, args) {
        args.get_webRequest().get_headers()['securityTicket'] = SECURITY_TICKET;
        alert('Security ticket: ' + args.get_webRequest().get_headers()['securityTicket']);
    }
</script>

    <%
    Response.Write(@"
        <script>
        function ResetPassword() 
        {
            var password = document.getElementById(""password"").value;
            var id = document.getElementById(""ctl00_ctl00_ContentPlaceHolder1_cphContent_hdnUsrID"").value;
            var d = {""userID"" : id, ""password"" : password };
            $.ajax
            ({
                type: ""POST"",
                url: """ + "" + @"http://localhost:2297/wwwroot/Services/UserService.asmx/ChangeUserPassword"",
                data: JSON.stringify(d),
                contentType: ""application/json"",
                dataType: ""json"",
                success: function() 
                {
                    document.getElementById(""password"").value = '';
                    alert('Success');
                    $(""" + "#ctl00_ctl00_ContentPlaceHolder1_cphContent_pnlChangePassword" + @""").fadeOut();
                    $(""html, body"").animate
                    (   {
                            scrollTop: $(""" + "#ctl00_ctl00_ContentPlaceHolder1_cphContent_pnlPerson" + @""").offset().top - 100
                        }, 1200);
                },
                error: function(msg) 
                {
                    if(msg === false) 
                    {
                        alert('Error');
                        return;
                    }
                }
            })
        }

        function passwordChanged_Success() { 
            alert('Changed');
        }

        function passwordChanged_Failed() { 
            alert('Failed');
        }
        </script>"); %>

The page includes an update panel.

The page's code behind:

private void GenerateSecurityTicket()
{
    string cacheKey = User.Identity.Name + ":securityTicket";
    string securityTicket = Guid.NewGuid().ToString();

    Cache[cacheKey] = securityTicket;

    string script = string.Format("SECURITY_TICKET = '{0}';", securityTicket);

    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "securityKey", script, true);
}

protected void Page_Load(object sender, EventArgs e)
{
    this.GenerateSecurityTicket();
}

Answer №1

Here is how my files are structured:

Students.aspx

<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="~/UserService.asmx" />
    </Services>
</asp:ScriptManager>
<script type="text/javascript" language="javascript">
    // JavaScript code here
</script>

UserService.asmx

<%@ WebService Language="C#" CodeBehind="~/App_Code/UserService.cs" Class="UserService" %>

UserService.cs

// C# code for UserService

Everything seems to be in place and should work fine. Let me know if there are any issues!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting problem with GZIP in Angular 2 application deployment

I have developed an Angular 2 TypeScript application. I am using Firebase for hosting and Cloudflare for optimizing speed, caching, and security. When checking the browser header, it indicates: accept-encoding:gzip, deflate, sdch, br The app.js file has ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

Get a Javascript file from Amazon S3 and run it within a Lambda function

Within S3, there exists a hello.js file that includes the following code snippet: function greet() { console.log(" From Greetings: "); } An AWS Lambda function written in NodeJS is attempting to access and execute this script. Despite having ...

Convert big integers in JSON to floating point numbers using exponentiation

Here is a snippet of code that I am working with: productID, err := products.Insert(map[string]interface{}{ "Properties": map[string]interface{}{ strconv.Itoa(propertyNameID): map[string]string{ "en": "Jeans Jersey", "n ...

Every time I refresh the page, the user is automatically logged out

I am currently working on developing an admin dashboard using nextjs 13. I have encountered a specific issue where the user is redirected to the login page every time they reload the page. Upon inspecting in developer mode, I noticed that cookies are still ...

Error message 800A03EA in Windows Script Host encountered while running Express.js script

I'm currently diving into the world of JavaScript development, following along with the guidance provided in the book called "JavaScript Everywhere." The book instructs me to execute the following code: const express = require('express' ...

Animation for maximum height with transition from a set value to no maximum height

While experimenting with CSS-transitions, I encountered an unusual issue when adding a transition for max-height from a specific value (e.g. 14px) to none. Surprisingly, there is no animation at all; the hidden elements simply appear and disappear instant ...

Is there a specific JSON schema designed for the SurveyMonkey API?

Currently, I am using the SurveyMonkey API to write Java code for survey analysis. The API provides JSON data which I need to manipulate efficiently and safely in my code by generating specific Java classes. However, despite my efforts, I have been unable ...

PHP is receiving data from $.post in an invalid format

I am facing a challenge in sending a JavaScript Object() to a PHP file in the correct format that $.POST requires. The PHP file does not establish any $_POST[] variables, which suggests that I may be transmitting the data in an improper format. JS: $(&ap ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

Pass JavaScript variables to a PHP file with the help of AJAX

Hey there, I'm new to developing web-based applications and currently learning about AJAX. I've run into a problem while trying to make an AJAX request with user inputs as variables and fetching the same variables in a PHP file. Below is the code ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

How come the loop is not removing the particular number I specified?

Could someone offer assistance? My code was functioning properly until I implemented a loop to check and remove any array that contains "0.00000000" as the value in the second index. It is now producing errors like "list index out of range.& ...

Adding to object in an external JSON file using javascript

I am working with an external file called file.json which contains the following values: { "number": "value" } My goal is to run a function that will append new data to the existing file instead of overwriting it. For instance, after running the func ...

The response from Moment.js shows the date as "December 31, 1969."

Currently, I am in the process of recreating one of FCC's backend projects: Upon testing my code, I noticed that when I input the following URL: http://localhost:3000/1 The result is as follows: {"unix":"1","natural":"December 31, 1969"} var e ...

Activate the feature of smooth shading using Three.js

When rendering an object with textures using MTL and OBJ files in Three.js, I encountered an issue where my model was displayed with flat shading. How can I enable smooth shading? var scene = new THREE.Scene(); var mtlLoader = new THREE.MTLLoader(); mtl ...

Encountering issues while trying to modify a JSON file using Python

My goal is to eliminate the array containing "Nike" under the "Shoe" variable. Below is the Json file I am working with: { "Shoes/Colorways": [ { "Shoe": "Nike", &q ...

The angularjs response data is mysteriously missing from the console display

I am struggling with the code below, as the data is not showing in the console log. I am new to Angular and would appreciate some help on how to display the data in HTML. this.$http.get(properties.client+'/123') .then(response => { ...

Filtering custom post types by category using REST API version 2 in WordPress

Currently developing an Android app utilizing the WP API. Successfully displayed a custom post type in the REST API accessible through: http://localhost/wordpress/wp-json/wp/v2/property Seeking to filter properties by their category, such as villa, home, ...

Guide to showing an uploaded image in a child component using Vue.js

Using the v-file-input component from Vuetify, I am able to upload images with the following code: <v-file-input label="Image" filled accept="image/png, image/jpeg, image/bmp" prepend-icon="mdi-camera" v-mod ...