The Springboot endpoint was successfully submitted through a fetch request, leading to a redirection to

Facing an issue while trying to submit a form to the /policy-holder page using fetch in JavaScript. The endpoint is redirecting to the login page, even though only admins are supposed to login. What could be causing this problem and how can it be resolved? I have already attempted to add permitted all to the security config for the endpoint, but with no success. Additionally, basic auth does not work simultaneously with cookie auth. How can this be fixed?

  @PostMapping("/policy-holder")
    public ResponseEntity<PolicyHolder> createPolicyAndBeneficiaries(@RequestBody @Validated PolicyHolderRequestDto policyHolderDto) {
        return policyHolderService.createPolicyAndBeneficiaries(policyHolderDto);
    }

Service.

 @Transactional
    public ResponseEntity<PolicyHolder> createPolicyAndBeneficiaries(PolicyHolderRequestDto policyHolderDto) {
        paymentGateway.verifyAccount(policyHolderDto.accountNumber(), "050");

        PolicyHolder ph =  PolicyHolder.builder()
                .accountNumber(policyHolderDto.accountNumber())
                .phoneNumber(policyHolderDto.phoneNumber())
                .lastName(policyHolderDto.lastName())
                .firstName(policyHolderDto.firstName())
                .email(policyHolderDto.email())
                .build();

        PolicyHolder savedPolicyHolder = policyHolderRepository.save(ph);

Security

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) ->
                        authorize.requestMatchers("/register/**","/css/**","/js/**", "/images/**").permitAll()
                        .requestMatchers("/").permitAll()
                        .requestMatchers("/index").permitAll()
                        .requestMatchers("/policy-holder").permitAll()
                                .requestMatchers("/users","/send").hasRole("ADMIN")
                                .anyRequest().authenticated()

                ).formLogin(
                        form -> form
                                .loginPage("/login")
                                .loginProcessingUrl("/login")
                                .defaultSuccessUrl("/users")
                                .permitAll()
                ).logout(
                        logout -> logout
                                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                                .permitAll()
                );

        return http.build();
    }

JavaScript

fetch('/policy-holder', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(extractedData),
    })
        .then(response => response.json())
        .then(data => {
            console.log('POST request response:', data);
            // Handle the response data as needed
        })
        .catch(error => {
            console.error('Error making POST request:', error);
            // Handle the error
        });

Answer №1

Spring security has been updated, now /error route requires authentication. If an error occurs, Spring attempts to access the route and redirects to the login page. To resolve the login error, I had to include the following fix. However, the root cause issue still needed to be addressed 😅

.requestMatchers("/error").permitAll()

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

Tips for including extra items in a JSON String using Angular 2

function execute(req:any): any { var stReq = JSON.stringify(req); // Adding additional item "Cityname": "angular2City" inside req req.Cityname = 'angular2City'; } Now, how can I include the additional item "Cityname": "angular2C ...

Automatically generate the first user on the Parse Server system

Is it feasible to programmatically create a User on Parse server without the need for sign up? More information can be found at https://github.com/parse-community/parse-server We attempted this using cloud code. var user = Parse.User(); user.setUserna ...

Sync Data Automatically from SQL Database

For the past two months, I've been researching how to achieve an effect similar to the auto-updating sales on the page. So far, I haven't had any luck. I do have a PHP file that counts the number of results in a database and displays them as a n ...

Utilize the Selenium driver to pick out the specific list item that you want

I am looking to select a specific element from a list of 8 items that contains the search text within its child div. The challenge is that the order of elements in the list changes frequently. I want to be able to identify and select the item that includes ...

A step-by-step guide on how to insert an image URL into the src attribute using the

The source of my image is -> src/assets/images/doctor1.jpg I would like to use this image here -> src/components/docNotes/docNotes.js In the docNotes.js file, I attempted -> <Avatar className={classes.avtar} alt="Remy Sharp" src ...

Error: Validation issues detected in field functionality

My goal is to loop through a set of text fields and check if the user has input any values. However, I'm facing an issue where even though I have provided values in the text fields, it seems like they are empty. To better illustrate my problem, I have ...

Tips for ensuring your jQuery events always trigger reliably: [Issues with hover callback not being fired]

My background image animation relies on the hover callback to return to its original state. However, when I quickly move the mouse over the links, the hovered state sticks. I suspect that I am moving the mouse off before the first animation completes, caus ...

Ways to retrieve the mapState property within a method

Is there a way to access the count property within the method while working with vuex? Take a look at my code provided below: Screenshot of Code: https://i.stack.imgur.com/xNUHM.png Error Message [Vue warn]: Computed property "count" was assigned to bu ...

The element is inferred to have the 'any' type. No index signature matching the parameter type 'string' was found on the 'User1' type

I have been experimenting with computed properties in TypeScript, but I've encountered a specific issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User1'. ...

Sending messages to all sockets in socket.io except the one who sent it

I'm currently working on integrating a chat feature into my app using socket.io. The process involves sending an API request to the server each time a user sends a message, which is then stored in the database. Only after this data storage step is com ...

How do you typically approach testing Cloud Code on Parse?

While working on developing a substantial amount of business logic in webhooks like beforeSave/afterSave/etc. using Parse.com, I have encountered some challenges as a JavaScript/Parse beginner. The process seems somewhat tedious and I'm questioning if ...

How can you effectively manage a Windows pop-up for downloading files and save them using Selenium and Java?

public static FirefoxProfile customFirefoxDriverProfile() throws Exception { FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("browser.download.folderList", 2); profile.setPreference("browser.download.manager.showWhenStartin ...

Display the value of the dynamically added selected element only

Is there a way to display the selected element value on click without showing all element values? In the code below, when I add usernames and click on any label, it should only show the corresponding delete icon. However, currently, it shows delete icons f ...

Tips for restricting the information retrieved from an API?

Currently, I am in the process of learning how to use AJAX with vanilla JS. My goal is to implement a limit on the amount of data received from an API, specifically restricting it to 10 objects maximum. The API url that I am working with can be found here ...

Placing a cookie using nookies within the Next.js API directory

I'm currently facing an issue while trying to use the nookies npm package to set a cookie within the Next.js api folder. I've successfully set up a cookie using the same code with nookies before, but for some reason, it's not working in this ...

Refreshing div content based on dropdown selection without reloading the page

I am currently working on implementing a dynamic dropdown feature that will update text content on a webpage without needing to refresh the entire page. The updated text will be fetched from a PHP function which receives input from the dropdown selection. ...

Discovering instances of a specific string within a larger string

My goal is to customize the default behavior of the alert function. Below is the code I am using: window.alert=function(txt) { waitOk='wait'; setMsgBox(txt); btnMsgOk.focus(); } However, I need this functionality to vary ba ...

Halt the Bootstrap carousel while entering text in a textarea

Is it possible to achieve this? I think so. I have created a carousel with a form inside. The form includes a textarea and a submit button. Currently, the slider does not slide if the mouse pointer is inside it, which is good. However, if the pointer is o ...

What is the process for converting a csv string into a format compatible with Spark-ML's Dataset<Row>?

I am working with a Dataset<Row> df, which consists of two columns ("key" and "value") both of type string. When I run the command df.printSchema();, the output is as follows: root |-- key: string (nullable = true) |-- value: string (nullable = tr ...

Linking an intricate property in ExtJS to a text field

Here is an example of JSON data: { name: { firstname: 'First Name', lastname: 'Last Name' } } How do I go about loading this data into a form field in ExtJS? First Name: [ First Name ] Last Name: [ Last Name ] UPDATE: After imp ...