What methods can I use to protect a JavaScript call to a Java Servlet through XMLHttpRequest to prevent unauthorized access if the URL is manually typed into a browser?

I have a current webpage that utilizes a piece of javascript to execute the following:

function initiateAction(parameter) {
    request = false;
    if (window.XMLHttpRequest) {
        try {
            request = new XMLHttpRequest();
        } catch (error) {
            request = false;
        }
    } else if (window.ActiveXObject) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (error) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (error) {
                request = false;
            }
        }
    }

    if (request) {
        var url_string = "/Servlet?parameter=" + parameter;
        request.open("GET", url_string, false);
        request.onreadystatechange = handleRequestChange;
        request.send(null);
        // process the response
    }
    return something;
}

My concern is that if someone manually enters the full URL into their browser window (e.g. "") the response is displayed. How can I prevent this and only allow the code to access the response?

Answer №1

If you're trying to determine whether a request was made using XHR, you can inspect the X-Requested-With header.

Boolean isXMLHttpRequest = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

You can find more information on this topic here.

Answer №2

Utilizing session frameworks such as Shiro and Spring Security can be beneficial. These frameworks ensure that only authenticated sessions are able to access resources (URLs), redirecting unauthorized users to a customized login page.

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

Options chosen will vanish in a multi-select drop-down tag with a scroll bar in HTML

I need assistance with my multiple drop-down select tag issue. .CustomStyle { overflow-x: scroll; width: 16%; } <select multiple size="5" class="CustomStyle"> <option>Option 1</option> <option>Option 2</option> &l ...

Real-time communication with all connected clients using WebSockets in Play Framework 2

Can someone help me understand WebSocket in Play Framework? Here is the code snippet from my controller: public static WebSocket<String> sockHandler() { return new WebSocket<String>() { // Called t ...

How can I access all the connected "guilds/servers" on this Discord bot?

When I try to access client.guilds, I receive an unfamiliar object that I am struggling to interpret. Object: GuildManager { cacheType: [Function: Collection], cache: Collection(1) [Map] { '11111111111111111' => Guild { // Guil ...

Is it true that Vue 3 + Inertia automatically removes event listeners upon component unmounting?

There is an event listener set up within the script setup block: <script setup> import {ref} from 'vue' const elementRef = ref(null) window.addEventListener('click', (event) => { if (!elementRef.value.contains(event.t ...

Tips for displaying a gallery of 5 images in a 2-row slider using bxslider

I've been attempting to create a unique image slider using bxslider. My goal is to have a 2-row slider with 5 images displayed in each row. However, I'm encountering difficulties when I try to integrate the HTML, CSS, and JavaScript code. Despit ...

What is preventing the calculation of the area in this scenario?

class TestShapes { public static void main(String[] args){ Scanner input = new Scanner(System.in); // creates the scanner class System.out.print("Enter the number of shapes: "); // asks user for input int N = input.nextInt(); // stores th ...

Redirecting from HTTP to HTTPS with node.js/Express

Are there steps I can take to modify my web application to operate on HTTPS instead of HTTP using node.js/express? I require it to run on HTTPS due to the use of geolocation, which Chrome no longer supports unless served from a secure context like HTTPS. ...

Verify whether an item exists within a group of objects, and if so, eliminate it from the group; otherwise, include it in the group

I am working on a function to create an array of objects where only specific attributes are kept from the original object. The goal is to check if the selected object is already in the array - if it is, remove it; if not, add it. However, I'm facing ...

The ScheduledThreadPoolExecutor is set to scheduleWithFixedDelay for timely and "urgent" task execution

I am facing a unique challenge for which the standard library does not provide an adequate solution. I am seeking any recommendations for alternative libraries that may address this issue, so I can avoid creating a custom workaround. My current task is s ...

Is there a way to retrieve a particular object from the state and access one of its elements?

I have a component called Tweets.js: import React, {Component} from "react"; export default class Tweets extends Component { constructor(props) { super(props); this.state = {tweets: [], users: []}; } componentDi ...

Managing multiple changes in input values within an object

Looking to update multiple input field values using the handleChange() method with a starter object that includes its own properties. The goal is to assign input field values to corresponding properties within the starter object. However, the current imple ...

fetch and modify data simultaneously in firebase

Is there a way to retrieve a value from a Firebase document and immediately update it? I am familiar with methods for updating documents and retrieving their values separately, but how can I accomplish both in one go? update firebase.firestore().collecti ...

Vuetify - Best practices for vertically aligning rows in a v-treeview component

Just getting started with Vue js, so pardon me if this is a silly question. I've scoured the internet and can't seem to find a solution. I'm working on a v-treeview displaying a folder structure, with descriptions of each folder in a separa ...

Adjust the text according to the selected checkbox option

I am attempting to update the displayed text based on whether a checkbox is currently checked or not. The value of the viewable text should reflect the user's selection. I believe I am close, but the functionality is not working as expected. <html ...

Can the `lang` attribute be used in a `style` tag to specify the CSS preprocessor language for VueJS? Are there any disadvantages to using this method?

Occasionally, I notice people incorporating code like this: <style lang="scss"> ... </style> <style lang="stylus"> ... </style> I checked the documentation for the style tag and found that lang is not a valid a ...

Utilizing Angular 2's Routerlink with *ngIf and Parameters

Currently, I am facing an issue with a routerlink that includes a parameter: http://localhost:4200/item/1 I am trying to figure out how to implement an *ngIf statement with a parameter.... Here is what I have attempted so far: <div *ngIf="router.url ...

Ways to activate javascript following a PHP submission?

It's a bit tricky to explain. function m(val){ var element=document.getElementById('othermethod'); if(val=='others') element.style.display='block'; else element.style.display=&apo ...

Upon my initial click of the delete button, all the notes vanished. However, after refreshing the page, everything was back to normal and functioning properly

After numerous attempts, I have exhausted almost all troubleshooting methods. I meticulously tested my API to rule out any issues related to it. Strangely, the problem only occurs upon initial page visit, but works flawlessly upon refreshing. Prior to cli ...

Determine if it's a leap year and find out the number of days in the current month (between

public static boolean isLeapYear(int year) { if ((year % 4) != 0) { return false; } else if ((year % 400) == 0) { return true; } else if ((year % 100) == 0) { return false; } else { return true; } } pu ...

Executing functions asynchronously with callbacks using Node.js setTimeout

I have a node.js app running with a process that executes every 500 milliseconds. Occasionally, the process takes longer than 500ms to complete which causes issues when using setInterval. To address this, we modified our approach to use setTimeout with a ...