Fede Fede - 1 month ago 4
Java Question

AngularJS SpringSecurity CORS issue

I'm setting up an Angular+Spring Security module to login and registering users.
When I register an user, everything is OK. The final step after register is automatically login but I'm having this error:


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


The angularJs side services:

.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("loggin correcto");
localStorage.setItem("session",{});
}, function(data){
alert("error login 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 is the CORS filter implemented on backend side:

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 {

private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

public SimpleCORSFilter() {
log.info("SimpleCORSFilter init");
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

if (request.getMethod().equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}


This the filter on web.xml

<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>
tesis.core.security.SimpleCORSFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>simpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


I'm confussed, this are the Chrome Network requests:
req/res

I don't realize what I'm doing wrong.
Thanks!

EDIT:
When I send request from same url http//localhost:8080/ works perfectly. From http//localhost:9000 spring always return SC_UNAUTHORIZED

This is the SecurityConfig

package tesis.core.security;

import org.springframework.beans.factory.annotation.Autowired;
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;

@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);
}


@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.formLogin()
.successHandler(authSuccess)
.failureHandler(authFailure)
.and()
.authorizeRequests()
.antMatchers("/**")
.permitAll();
}
}


The AuthSuccess and AuthFailure class

package tesis.core.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class AuthSuccess extends SimpleUrlAuthenticationSuccessHandler{

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {

response.setStatus(HttpServletResponse.SC_OK);
}

}

package tesis.core.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

@Component
public class AuthFailure extends SimpleUrlAuthenticationFailureHandler{

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}

Answer

Finally I was able to find the solution. First of all, to solve the 401 error, I rewrited the request as it says here: 401 solution

After that, a new error appeared:

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

Then, reading Spring doc I realized that I must say specifically to spring which header to use. Here the clue: Spring Doc: header-static

So, this is the SecurityConfig file fixed:

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();
    }
}

Thanks to everyone.

Comments