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

Connectivity issue: Socket.io fails to register user upon connection

Upon connecting to the page, I expect to see the message 'a user connected' printed on the command line using node.js. However, this message is not being displayed, indicating that the user's visit to the page is not being registered (all ac ...

Error occurs when an arrow function is called before its function definition

console.log(addB(10, 15)); function addB(a, b) { return a + b; } console.log(addC(10, 15)); const addC = (a, b) => { return a + b; }; I attempted to convert a function into an arrow function and encountered the error "Cannot access 'addC&ap ...

Is there a way to integrate a MySQL database with parcel-bundler in a Node.js environment, or is there a simpler method to achieve this database integration with parcel-bundler?

Node.js and parcel-bundler are new to me, but I've managed to create a server.js file that connects to the database without any issues. Server.js const express = require('express'); const mysql = require('mysql'); //Establish con ...

Utilizing CSS Grid to arrange child elements inside their respective parent containers

I am currently working on a grid container that contains multiple divs. Each div houses different elements such as headings, paragraphs, buttons, and logos. I have utilized Flexbox to evenly distribute the logos across the container's width. However, ...

AngularJs Number Formatting: A Step-By-Step Guide

Is there a way to format a number from 10000 to 10,000.00 using only HTML and the ng-Model directive, without involving the controller file? I attempted to achieve this in the controller file through logic, but it always returns the number in the "10,00 ...

Ensure the presence of an editable column within a table using a jQuery function

Within the table, the first column is editable. Upon making a change to it, I want an alert to appear indicating that a change has occurred. The check function is being called after a delay of 5000ms. Embedding Code Snippet for Reference I suspect there ...

Using Ajax and PHP to store multiple checkbox selections into the database

I currently have 32 checkboxes on my page that I need to track the checked status for. In my JavaScript, I am looping through each checkbox and assigning a value of '1' for checked and '0' for unchecked. // Example for one checkbox if ...

Exploring the Depths of Javascript Variable Scope

bar: function () { var cValue = false; car(4, function () { cValue = true; if (cValue) alert("cvalue is true 1"); }); if (cValue) alert("cvalue is true 2"); } car: function (val, fn) { fn(); } I have encountered a similar is ...

Using jQuery, extract the input value and verify its accuracy. If correct, display the number of accurately predicted results

I am attempting to extract the value from an input field and validate if the answer is accurate. Rather than simply indicating correctness, I aim to analyze and display the number of correct responses alongside incorrect ones. Encountering difficulties wit ...

How to build custom middleware with parameters in Node.js

I'm working on creating a middleware in nodejs for access levels, and I've written the following middleware: class AccessUser extends middlware { async AccessUser(access,req, res, next) { const getTokenFrom = (req) => { const autho ...

SecretKey is not valid, FirebaseError code: 400

Currently, my backend is powered by Firebase. However, when I initiate it using NODE_ENV=debug firebase emulators:start --inspect-functions, the following messages are displayed: emulators: Starting emulators: auth, functions, storage ⚠ functions: Ru ...

The error callback encountered {"readyState":4,"status":200,"statusText":"success"} while processing

When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...

Creating a sidebar with child elements in Vitepress: A beginner's guide

I'm having trouble displaying my folder tree in the sidebar. When I click on a parent element like Group, the children elements are not showing up as expected. One strange thing is that the Group elements do not have the CSS property cursor: pointer ...

Displaying customized local JSON information in a Tabulator Table

I'm trying to incorporate local JSON data into a table using Tabulator. Specifically, I want to display the element obj.File.Name from the JSON. While I can render the data in a regular table, I face issues when trying with Tabulator as the data does ...

Implementing material-ui Snackbar as a global feature: a step-by-step guide

Currently, I'm in the process of building my react application using material-ui's Snackbar feature. With a plethora of components in my project, I prefer not to include <Snackbar/> in every single one of them. Is there a method to develop ...

How can a method inside an object property of the same class be invoked in JavaScript?

I'm faced with a bit of confusion here. I have a class property called hotspot of type object, declared as follows: Cannon.prototype.hotspot = {stuff: this.blah(...) }; The method blah() is actually a prototype of the same 'class': Canno ...

An unusual 'GET' request has been made to the '/json/version' endpoint in Express.js

Hey there, I'm facing a challenge with my Express project. For some reason, I keep receiving a 404 error due to a mysterious GET request to '/json/version'. The request seems to bypass the defined routers after adding session data and eventu ...

What are the steps to use grunt for running a node.js application?

Directory Structure: myapp --public(directory) //contains files related to public (AngularJS, CSS, etc) --server(directory) //contains files related to server --server.js Code server.js //located at root directory ---------------------- ... var app = ...

Resolving issues with jQuery input values

I have been working on a form that allows users to choose an amount or specify another amount. When the user clicks on "other amount," it changes the displayed amount to $5. My goal is to make it so that when the user specifies an amount other than 5, it u ...

Retrieving data from JSON in JavaScript

Extracting data from a JSON file and using a JavaScript script to visualize it through a graph. JSON file link: The JavaScript code responsible for drawing the graph is as follows: $(document).ready(function(){ google.charts.load('current', ...