What's the reason behind my REST API delivering a 401 error code?

New Update

After being encouraged to implement debug logs, I have discovered that the issue lies with Spring reporting an invalid CSRF token for the notices controller. I have compared the headers generated by Postman and the fetch requests, but found no discrepancies. The token is successfully placed into the request header, yet nothing significant is appearing in the Spring logs, so the debugging process continues.


Currently, I am delving into learning Spring Security and connecting the React frontend to the Spring backend. I am facing challenges as the POST request made to the desired endpoint results in a 401 error. I have ensured that CORS is properly configured and the endpoints are permitted, making this error confusing to me.

In essence, the process involves calling an endpoint /token to acquire a CSRF token, and then calling /notices while passing the token as a header. Using Postman works flawlessly, leading me to initially suspect a CORS issue. However, running the frontend on a different port also triggers a CORS block, indicating that the problem may lie elsewhere.

Additional information:

  • /notices and /token are both POST operations.
  • Both the Spring backend and React frontend are operating on the same local machine.
  • Error code 401 is being received.

The JavaScript code for the frontend call is as follows:

const debugNotices = () => {
  let tokenData:any;
  fetch('http://localhost:8080/token', {method:"POST"})
  .then((response) => response.json())
  .then((data) => tokenData = data).then((data:any) => fetch("http://localhost:8080/notices", 
  {
    method:"POST",
    headers: {
      "X-XSRF-TOKEN": tokenData.token
    }
  }))

}

Below is the Spring security configuration:

@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        
    http
        .cors()
            .configurationSource(new CorsConfigurationSource() {
            
                @Override
                public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                    CorsConfiguration config = new CorsConfiguration();
                    
                    config.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
                    config.setAllowedMethods(Collections.singletonList(("*")));
                    config.setAllowCredentials(true);
                    config.setAllowedHeaders(Collections.singletonList("*"));
                    config.setMaxAge(3600L);
                    return config;
                }
            })
            .and()
        .csrf()
            .ignoringRequestMatchers("/contact", "/register", "/token")
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 
            .and()
        .securityContext()
            .requireExplicitSave(false)
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and()
        .authorizeHttpRequests()
            .requestMatchers("/myAccount", "/myBalance", "/myLoans", "/myCards", "/user").authenticated()
            .requestMatchers("/notices", "/contact", "/register", "/test", "/token").permitAll()
            .and()
        .httpBasic()
            .and()
        .formLogin();
        
    return http.build();
}

I have attempted including credentials:'include' in the request body, but it triggers a login prompt that does not align with the intended direction.

Moreover, I have tried manually inserting the CSRF token instead of fetching it from the server, yielding the same unsuccessful outcome.

CORS has also been thoroughly tested to the best of my knowledge, and any attempts to access the endpoints from sources other than localhost:3000 are denied with an expected CORS error.

Answer №1

The problem arises only when accessing the React frontend from localhost:portNumber. I managed to overcome the problem entirely by substituting my local IP address for localhost.

For instance, 192.168.0.105:3000.

I am still unsure of the reason behind the issue when using localhost in the URL, and would appreciate any insight you may have on this matter.

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

Utilizing a loop to extract and display JSON data within a table

In the process of building a website using Laravel, I encounter a JSON response from the server that looks like the following: [{"id":1,"user_id":"1","patient_name":"kk","age":"44"," ...

What is the best way to extract JSON HTML values in an Android app?

Can anyone help me figure out how to properly parse a JSON feed in my Android app? The issue I'm facing is that the JSON feed from my blog contains HTML values. Below is the link to the feed: For example, here is a snippet from the feed: "content": ...

Creating a personalized React date selection tool using TypeScript

After following the instructions in the documentation for creating a custom datepicker, I finally managed to build one. However, I encountered an error stating "Function components cannot be given refs. Attempts to access this ref will fail. Did you mean ...

During the build process, NextJS encountered an issue locating the constants.js module

I encountered an error while executing next build using next version ^10.2.3. I attempted to remove the node_modules and .next folders, then reinstalled dependencies with npm install && next build, but the issue persists. Error: Cannot find mod ...

Is there a beginner's pack or trial version available for utilizing TypeScript with IBM Cloud Functions / OpenWhisk?

While working on developing actions in IBM Cloud Functions, I have been primarily using Node.js / Javascript and Python for coding. However, I haven't come across specific instructions on how to incorporate TypeScript into IBM Cloud Functions. I am c ...

Iterate through a nested array in JavaScript and extract specific properties by comparing them to another array

Within my code, there is a kids object structured as follows: const kids = { name: 'john', extra: { city: 'London', hobbies: [ { id: 'football', team: &apos ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

Building a responsive menu bar from JSON with Angular Material: A step-by-step guide

My attempt to recursively create a menu bar using the Angular Material Menu Bar directive isn't yielding the desired outcome. The current approach involves creating a directive and calling it recursively, as demonstrated in this example: https://plnkr ...

"Supporting Python object serialization into JSON with the ability to choose specific attributes

I am having trouble converting my object to and from JSON. Because this object utilizes SQL Alchemy, the regular json.dumps(vars(self)) method is ineffective. I am in search of the correct syntax to achieve this task. def to_json(self): obj = ...

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

In search of a simple solution for parsing JSON efficiently

I'm currently working on parsing JSON data using Java language: { "student_id": "123456789", "student_name": "Bart Simpson", "student_absences": 1} Can someone suggest a more efficient method to achieve this? I have attempted the code below but feel ...

Adding numbers using the JOLT binary system is a seamless and

Can you help me convert the JSON data below using JOLT? The input will be an array of strings Each string represents a binary number (0 or 1) I need to add these binary numbers together and then separate each resulting bit as its own property { "b ...

The Jquery Ajax image loading function will only work successfully when an alert statement is included within the $(window).one function

I'm facing a unique challenge. I am loading a JSON file containing the src, width, and height of multiple images. My goal is to load them into the smooth script jQuery plugin and automatically scroll through the images. The "viewing area" div can ac ...

The error message is indicating that the property `match` is being attempted on an undefined object. This issue is puzzling as it does not reference any specific files or

I encountered an issue while working on my project: I kept receiving the error message "Cannot read property match of undefined." Cannot read property 'match' of undefined The error points to a specific line in polyfills.js: process.version.ma ...

Error encountered in React TypeScript: Expected symbol '>' was not found during parsing

While transitioning from JavaScript to TypeScript, I encountered an error in my modified code: Error on Line 26:8: Parsing error: '>' expected import React from "react"; import { Route, Redirect, RouteProps } from "react-router ...

Trouble with styling the Ngx-org-chart in Angular

I integrated the ngx-org-chart library into my Angular project, but I'm facing issues with the styles not applying correctly. Here are the steps I followed: I first installed the package using: yarn add ngx-org-chart Then, I added the ngx-org ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...

What is the best way to interpret a line break within a string variable in TypeScript?

Realtime Data base contains data with \n to indicate a new paragraph. However, when this data is retrieved and stored in a String variable, the website fails to interpret the \n as a paragraph break: https://i.stack.imgur.com/tKcjf.png This is ...

Create a function that takes advantage of a Promise to resolve its actions

In the asynchronous function provided below: export default async function getUserNames(id: string[]): Promise<string[]> { let userNames: string[] = []; // Additional actions such as service calls are performed here... return userNames; ...