0
votes

I was following the tutorial from Spring Blog (https://spring.io/guides/tutorials/spring-security-and-angular-js/). But I started with an existing Spring application, therefore I am not using Spring Boot to start with and I have to find a way to implement the components in XML and Java Configuration hybrid style.

Here is my CORS filter:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {

    public SimpleCORSFilter(){

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) resp;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //x-auth-token is a custom header for Spring Security AngularJS implementation
        response.setHeader("Access-Control-Allow-Headers", "Options, authentication, authorization, X-Auth-Token, Origin, X-Requested-With, Content-Type, Accept, XSRF-TOKEN");
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            System.out.println("OPTIONS request from AngularJS");
            response.setStatus(HttpServletResponse.SC_OK);
        }
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {}

and here is my CsrfHeaderFilter.java, pretty much just copied from the tutorial:

@Component
public class CsrfHeaderFilter extends OncePerRequestFilter{

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        System.out.println("CsrfHeaderFilter vvv");
        CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
        if(csrf != null){
            Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
            String token = csrf.getToken();
            System.out.println("CSRFToken Value: "+token);
            if(cookie == null || token != null && !token.equals(cookie.getValue()) ){
                cookie = new Cookie("XSRF-TOKEN", token); //use XSRF-TOKEN as the response header for CSRF token
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        System.out.println("CsrfHeaderFilter ^^^");
        filterChain.doFilter(request, response);
    }

and CsrfHeaderFilter is configured to be after Spring's CsrfFilter:

<sec:custom-filter ref="csrfHeaderFilter" after="CSRF_FILTER" />
<sec:csrf token-repository-ref="csrfTokenRepository"/>

csrfTokenRepository:

@Configuration
public class CustomCsrfTokenRepository {

    @Bean
    public CsrfTokenRepository csrfTokenRepository(){
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        repository.setParameterName("_csrf");
        return repository;
    }
}

I have my own Authentication Filter with a custom login URL:

public class CustomerAuthenticationTokenProcessingFilter extends AbstractAuthenticationProcessingFilter{

    private static final String SECURITY_TOKEN_HEADER = "x-auth-token";
    private static final String AUTHORIZATION_HEADER = "authorization";

    @Autowired
    private CustomerTokenAuthenticationService tokenAuthenticationService;

    @Autowired
    CustomerAuthenticationService customerAuthenticationService;
    @Autowired
    @Qualifier("customerAuthenticationManager")
    AuthenticationManager authenticationManager;

    protected CustomerAuthenticationTokenProcessingFilter(){
        super("/company/login"); 
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
            Authentication authentication = null;
            //Authentication Logics...
            ...
        return authentication;
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            Authentication authResult) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authResult);
      }
}

and of course, a custom logout url:

<sec:logout invalidate-session="true" delete-cookies="JSESSION,XSRF-TOKEN" 
    logout-url="/resource/logout" success-handler-ref="customerLogoutSuccessHandler"/>

customerLogoutSuccessHandler:

public class CustomerLogoutSuccessHandler implements LogoutSuccessHandler{

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

        if (authentication != null && authentication.getDetails() != null) {
            try {

                SecurityContextHolder.clearContext();
                System.out.println("User Successfully Logout"); 
                response.setStatus(HttpServletResponse.SC_OK);

            } catch (Exception e) {  
                e.printStackTrace();  
                e = null;  
            }  
        }  
    }

}

The AngularJS code is pretty simple. Originally I show the login form and just do a HTTP POST request to the Spring's /company/login endpoint, but somehow my AngularJS application is not getting the CSRF token it needed... So i added a HTTP GET request at startup to request from an open URL (access="permitAll()") in order to get the XSRF-TOKEN for my upcoming requests. Login and logout works fine until I login again. The error is "POST http://localhost:8080/company/login 403 (Forbidden)" and "Invalid CSRF Token was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'"

I think there is something wrong with cookies in my browser. I can see the same XSRF-TOKEN from before being pass to Spring when I output the cookie data in my CORS filter, and Spring's CsrfFilter denied further request because the CSRF token is not correct.

FilterChainProxy DEBUG - /company/login at position 3 of 14 in additional filter chain; firing Filter: 'CsrfFilter'
CsrfFilter DEBUG - Invalid CSRF token found for http://localhost:8080/company/login

Maybe I am missing some functions on the logout part? How can i update the XSRF-TOKEN if my request never get pass Spring's CsrfFilter?

Please feel free to ask me for more detail if necessary. I really want to get this issue solved because I already spent so much time trying to figure out what is wrong :(

1

1 Answers

0
votes

So, not long after I posted this answer, I figured out the issue...

The backend server configuration is fine, the problem is actually from the AngularJS HTTP request. Since I am following the tutorial from Spring blog, I am also using the AngularJS code from the tutorial because I am fairly new to AngularJS. I created more functions and controllers to fit what i need and I am using $http.get with .success() and .error(), which is an asynchronous call. Somehow this is causing the Csrf Token issue. All these asynchronous http request is making me very confused. So i decided to find a way to wait until the Http request to finish before the next Http request and see what happens. I have a factory to handle the login and logout.

This is probably not the best way to do it, but here is part of the AngularJS code:

//Move the initial GET request to a variable
            var init = function(){
                  return $http(
                            {
                                url : '/my/url/',
                                method : 'GET',
                            }
                  ).then(function(result){
                      //bunch of debugging messages
                      return result.data;
                  })

            }

Here is how to invoke my initial GET request to get the CSRF token, and then make the login POST request after the GET request is done:

                var initPromise = init();
                initPromise.then(function(result){
                    $http(
                            {
                                url : '/url/to/login',
                                method : 'POST',
                                headers : headers
                            }
                    ).success(function(data, config, headers) {
                       //debugging messages of course
                        //getting my data
                        ...

                        if(data_validation_is_true){
                            $http({
                                url : '/my/secured/resource/url',
                                method : 'GET',
                                headers : 
                                {
                                    'X-Auth-Token' : token_I_Received
                                }
                            }).success(function(data, config, headers){
                                console.log('/inventory/resource/user request with token, response headers: '+JSON.stringify(headers()));
                                if (authenticated) {
                                      //authentication successful logic
                                      ...
                                    } else {
                                      //authentication unsuccessful logic
                                      ...
                                    }

                            }).error(function(data){
                                //error handling
                                ...
                            });
                        }
                      }).error(function(data, status) {
                        //error handling
                                ...
                      });
                })

Please give me any suggestion if there is anything wrong.