Challenges with CORS in AngularJS and Spring Security

I am currently in the process of setting up a module that combines Angular with Spring Security for user login and registration purposes. Everything seems to be working fine when I register a new user. However, I am encountering an error when the final step of the registration process, which is supposed to automatically log in the user, fails with the following message:

XMLHttpRequest cannot load http//localhost:8080/com-tesis/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. The origin 'http//localhost:9000' is not allowed access. The response received a HTTP status code of 401.

On the AngularJS side, the services are structured as follows:

.factory("sessionAccountService", function($http){
        var session = {};
        session.login = function(data){
            return $http.post("http://localhost:8080/com-tesis/login",
                              "username="+data.name+"&password="+data.password,
                              {headers: {"Access-Control-Allow-Headers":"Content-Type"}}
            ).then(function(data){
                alert("Successful login");
                localStorage.setItem("session",{});
            }, function(data){
                alert("Error logging in");
            });

        };
        session.logout = function(){
            localStorage.removeItem("session");
        };
        session.isLoggedIn = function(){
            return localStorage.getItem("session") !== null;
        }
        return session;
    })
  .factory("accountService", function($resource){
        var service = {};
        service.register = function(account, success, failure){
            var Account = $resource("http://localhost:8080/com-tesis/rest/accounts");
            Account.save({},account,success,failure);
        };
        service.userExists = function(account, success, failure){
            var Account = $resource("http://localhost:8080/com-tesis/rest/accounts");
            var data = Account.get({name:account.name}, function(){
                var accounts = data.accounts;
                if (accounts.length !== 0){
                    success(accounts[0]);
                } else {
                    failure();
                }
            }, 
            failure);
        }
        return service;
    });

This CORS filter is implemented on the backend:

package tesis.core.security;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class SimpleCORSFilter implements Filter {
    // Code implementation here
}

The filter is defined in the web.xml file as well.

Upon inspecting the Chrome Network requests, I am still unable to determine the cause of the issue. Any assistance would be greatly appreciated!

EDIT: Requesting from the same URL (http//localhost:8080/) works perfectly fine. However, when requesting from a different URL (http//localhost:9000), Spring consistently returns SC_UNAUTHORIZED.

Answer №1

At last, the solution was within reach. To tackle the 401 error, I followed the steps outlined in this helpful guide: 401 solution

However, a new obstacle presented itself:

An issue arose stating 'No 'Access-Control-Allow-Origin' header is present on the requested resource Origin is therefore not allowed access.'

Upon consulting the Spring documentation, it became clear that I needed to specify to Spring which header to utilize. The answer lies here: Spring Doc: header-static

With that knowledge in hand, I made the necessary adjustments to the SecurityConfig file:

package tesis.core.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.header.writers.StaticHeadersWriter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private AuthFailure authFailure;

    @Autowired
    private AuthSuccess authSuccess;

    @Autowired
    private EntryPointUnauthorizedHandler unauthorizedHandler;

    @Autowired 
    private UserDetailServiceImpl userDetailService;

    @Autowired
    public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception{
        builder.userDetailsService(userDetailService);
    }

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new SimpleUrlAuthenticationFailureHandler();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .headers().addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin","*"))
            .and()
            .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
            .formLogin()
                .successHandler(authSuccess)
                .failureHandler(authFailure)
            .and()
            .authorizeRequests()
                .antMatchers("/**")
                .permitAll();
    }
}

Gratitude to all who helped on this journey.

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

Unable to send WhatsApp messages using Java

I'm seeking assistance to tackle this issue. My plan involves sending a WhatsApp message using Java with the help of a WhatsApp Gateway. Below is the Java code: import java.net.*; import java.io.BufferedReader; import java.io.OutputStream; import java ...

I am wondering about the proper method for deleting multiple records simultaneously in Ember Data

My current challenge involves managing a list of record IDs, such as [1, 20, 20]. The process of individually querying and deleting each item is proving to be quite inefficient. store.findRecord('post', 1).then(function(post) { post.deleteRec ...

Angular JS scope value fails to update in a separate browser tab

I recently created a sample page with AngularJS. After submitting comments in a textbox, the values are added to a scope variable and displayed on the same page using ng-repeater. Everything seems to be working correctly. However, when I open the page in ...

Is there a way for me to verify the well-being of a particular AWS service within a designated region?

I've been working on verifying the availability and health of an AWS service in a specific region. For example, I've been utilizing AWS-provided endpoints like this one for Lambda: https://docs.aws.amazon.com/general/latest/gr/lambda-service.htm ...

Replicate and modify the settings on a fresh radio inspection

In my approach, I am avoiding direct HTML editing and instead utilizing JavaScript/jQuery to accomplish the desired outcome. Initially, one input (specifically 'Express Shipping') is pre-selected by default. The goal is to clone/copy the HTML co ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...

The `background-size` property in jQuery is not functioning as expected

I am facing the following issue: When I click on a div with absolute positioning, I want to animate its position, width, and height. In addition, I want to change the background-size using jQuery. However, the problem is that all CSS properties are updat ...

Error encountered when attempting to instantiate a JSON object from a string

I am trying to convert a string retrieved from a server into a JSON object. Even after replacing the double quotes with backslashes, I am still encountering an error. Here is the JSON data: { "tasks": [ { "id": "activiti$1942", "descr ...

How the Marvel of jQuery Ignites the Power of

I require some assistance with the callbacks. It appears that they are not functioning properly. I am in the process of creating a jQuery-based game. I have designated a <div id='button'></div> for all the buttons that will be used ...

AngularJS form submission sends data to a specific URL saved within the model for processing

I'm facing an issue with my angular application where I need to submit a form to a vendor. The vendor specifies the URL each time the process runs, and then the application submits to that specific URL. After submission, the vendor redirects the clien ...

Form fields in Bootstrap 4 will consistently expand downward in the select dropdown menu

When using bootstrap 4, I want my field to always expand downwards and never upwards, even when half the screen is taken up by the form's select element. How can I achieve this effect? I have tried using data-dropup-auto="false" but it didn't wo ...

Selenium Java: Mastering the Art of Dragging and Dro

When using Selenium, I attempted to drag and drop content into a search-textbox. However, the drag operation is successful but the dropping part into the search-textbox does not work as expected. Can someone provide guidance on how to successfully drop t ...

Encasing a series of AJAX calls in a function: Implementing JavaScript and JQuery

I am facing an issue with a chain of two AJAX requests within a forEach() loop, where the second request relies on the response of the first. I have tried to wrap this code block in a function for reusability, but it seems to stop working. As a beginner in ...

How to encase HTML content within a scope variable without relying on ng-bind-html

Is there a way to include HTML content using a scope variable in AngularJS without utilizing ng-bind-html-unsafe? <div ng-controller="dataController">{{test}}</div> $scope.test = "<div>Html content</div>" ...

What steps can I take to prevent my JavaScript code from interfering with my pre-established CSS styles?

I'm currently designing a mini-email platform that serves as a prototype rather than a fully functional application. The HTML file contains placeholder emails that have been styled to appear presentable. I've implemented an input bar and used Jav ...

Dialog in Angular Material refuses to close even after calling the dialog.close() function

I've been struggling with this issue for a while, hoping someone can assist. In my Angular project, I have a login component with a dialog that opens a new popup window. Upon successful login, this window closes and triggers the following function: l ...

What causes the transformation of [{"value":"tag1"} into [object Object] when it is logged?

Currently on my node.js server, the code I'm using is as follows: var tags = [{"value":"tag1"},{"value":"tag2"}]; console.log("tags: " + tags); My expectation was to see this in the console: tags: [{"value":"tag1"},{"value":"tag2"}] However, what ...

Exploring the search feature within Redux and React-Native

The search functionality in redux is giving me some trouble. I have written the following code for it, but strangely enough, it's not working properly. Interestingly, the same code works perfectly when used without redux. searchItems: (name ) => ...

Retrieve the child grid's data source in Kendo using Angular

I am currently working with a master detail grid in Kendo Grid and using the Angular version of the Kendo Grid. One interesting feature I have added is a custom button for adding a new record in each row of the grid. When this button is clicked, a new rec ...

Ways to avoid running any cucumber-jvm scenarios if the initial scenario fails

I have 8 scenarios using cucumber-jvm, with the very first scenario focused on measuring page load time and checking environment availability. If this initial scenario fails, such as due to an unavailable environment or slow loading times, I want all other ...