Stopping unauthorized users from manipulating REST URLs

I am currently exploring methods to prevent an exploit where a user manipulates the URL, specifically in a GET request scenario. The following code represents a route on my Express router that processes incoming requests for a certain collection "A" and retrieves specific items from it.

router.get("/word/:collection/:language/:amount", function(req, res) {
   getItems(req, res);
}

If a user alters the ":collection" section of the URL in the front-end JavaScript to "B", they will access collection "B". How can I address this issue? While I can restrict access to collections containing userIDs based on req.user, in this case, both collections A and B need to be accessible by the user at different times, so outright denial is not an option. My goal is to prevent unauthorized access to these collections when it's inappropriate (as they are used in distinct pages).

Answer №1

It is crucial to secure REST endpoints that contain sensitive information accessible only to certain users. The common methods of securing such endpoints include passing an API token, using oAuth tokens, or a login cookie. If userA should not have access to collectionB, it is necessary to perform a validation check within the resource and return an appropriate error code to the browser.

One commonly used error code for unauthorized access on websites is 401: Unauthorized. Here is a straightforward example:

router.get("/word/:collection/:language/:amount", function(req, res) {
    if ( !hasAccess(req.params.userToken) )
    {
        return res.send(401, {success: false, message: 'no permission'});
    }
    var collection = req.params.collection,
    var language = req.params.language,
    var amount = req.params.amount;
    return getItems(req, res, collection, language, amount);
}

Edit: Upon revisiting your question, I now understand that the user may need access to both collections at some point. Even in this scenario, server-side validation is still necessary. Here's another example involving quizzes and answers:

router.get("/quiz/finish/:id", function(req, res) {
    //Record that this user has completed this quiz
    return recordQuizAnswers(req.params.userToken, req.params.quizAnswers);
}

router.get("/quiz/answers/:id", function(req, res) {
    //Has this user completed this quiz?
    if ( !hasUserTakenQuiz(req.params.userToken) )
    {
        return res.send(401, {success: false, message: 'Trying to access answers without completing quiz? Cheater...'});
    }
    return getQuizAnswers(req.params.id);
}

Edit 2: Based on your comment, here is another solution you can consider. Utilize UUID's for IDs rather than auto-incrementing numbers. This approach will prevent users from manipulating IDs to access different quizzes.

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

Enhancing transparency with a touch of background color

After successfully exporting my chart created in canvas as an image file, I noticed that the image turned out to be transparent without any background. Is there a way through code to add a background color to this existing image obtained from canvas? For ...

Utilize Set.Attribute prior to entering the for loop

Could someone please clarify why I am unable to declare the var node before the for loop and then simply use appendChild(node) inside the loop? Why is it necessary to declare it for each iteration in order for it to affect all div elements? Otherwise, it w ...

jQuery mobile not recognizing the ID we specified

I am in the process of developing an audio application. My goal is to change the id of the Play button dynamically to "paused" when it is clicked. However, despite my efforts, clicking on the "paused" button does not pause the audio as intended. $(&ap ...

Exploring asynchronous data handling in AngularJS using promises

Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data. In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asy ...

Choose the heading element based on its class

I am trying to target a specific element by its class and store it in a variable, but I specifically need this element to be a heading element. To clarify: at any given time, there are always exactly 3 elements with this particular class on my page: an < ...

query the database to retrieve information from a dropdown menu that shows connected services using the CodeIgniter framework

I am currently utilizing both Codeigniter and bootstrap in my project. Within my project, I have two select options named "service" and "sub-service". The values for these options are stored within an array. Here is a visual representation of the options: ...

Modify JSON date format to a shorter version using the first 2 letters of the month and the year

Looking to convert date values in a JSON array from "December 2016" format to "D16". Hoping to accomplish this using Regex, any assistance would be greatly appreciated. [["November 2016","December 2016","January 2017","February 2017","March 2017"],["tot ...

Adjust the hue of a specific node

Is there a way to customize the color of an individual node in an eChart treemap? I attempted to set a color property for the node, but it didn't seem to work. While I was able to change the label's color, I'm interested in changing the back ...

Issue: Unable to execute UserModel.create as a function

When working with mongoose to create a new document within my POST Route handler, I am facing an issue. My routes are defined using express.Router in the index.js file: index.js const express = require('express'); const app = express(); const us ...

Leveraging AngularJs with MongoDB and Mongoose

I am working on connecting AngularJS with MongoDB using Mongoose. My goal is to pass the Models to controllers so that I can utilize $scope to access the data. I am unsure about setting up an Angular Service for this purpose, and would appreciate any guida ...

AngularJS: Toggle footer visibility with custom message

My goal is to develop an Angular app using Intel XDK with 3 page scripts in index.html, each having a separate footer. The requirement is for the footer and its message to display and hide every 5 seconds when running each page. app.js app.controller(&ap ...

How can Javascript or Jquery determine the specific event assigned to an object?

Is it possible to retrieve the properties of HTML elements using their name or id? For example: document.getElementById('id').value; //Accessing element property in JavaScript $('#id').attr('class'); // Accessing correspond ...

Executing a node.js function within an Angular 2 application

Currently, I am running an Angular2 application on http://localhost:4200/. Within this app, I am attempting to call a function located in a separate node.js application that is running on http://localhost:3000/. This is the function call from my Angular2 ...

Error code 12004 encountered during the execution of a service request

While working on a service call in my JavaScript code that retrieves XML data using XMLHttpRequest, everything runs smoothly in Chrome and Firefox, successfully fetching the data over HTTPS. However, when attempting to execute the same code in IE11, it ret ...

Experiencing challenges with socket io connectivity between my backend and Quasar application. Encountering a 403 Forbidden error while trying to establish a connection with

I recently updated my Quasar app and ran into issues with the websocket connection after switching from development to production mode. The app is hosted on an Express server via pm2 on my Ubuntu server, which also connects to a database. Here are some sn ...

Encountering an "Unspecified Reference Error" while attempting to retrieve data from an API in your

I've been attempting to utilize a mock API from in order to fetch data for my Next.js application. However, I am consistently encountering an undefined reference error, despite following the code snippet provided in the official Next.js documentation ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

The process of filtering and outputting JSON data in JavaScript or jQuery

There is JSON data available for review. var data = [{ "gender": "male", "name": { "first": "rubween", "last": "dean" } }, { "gender": "male", "name": { "first": "rubween", "last": "dean" } }, { ...

Having difficulty executing the command 'npm install -g expo-cli'

When attempting to execute npm install - g expo-cli on a Windows 10 machine, I am encountering issues. An error message keeps popping up and preventing me from proceeding. I'm in desperate need of assistance! npm WARN deprecated <a href="/cdn-cgi/ ...

When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with: <button class="pop-btn"> Pop </button> While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript: const Population_div_Button=document. ...