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.