2
votes

I am using Spring session and Spring security for my REST API, but encountered a problem when I enabled CORS via a simple filter.

  1. If I used a relative URI by http proxy(map http://xxxx/api to /api in client app), it works well.
  2. If I used the full URL directly, I encountered a problem when used CORS, it can not fetch the session info, the following is the Spring security log.
    2015-02-11 10:46:57,745 [http-nio-8080-exec-29] DEBUG   org.springframework.security.web.FilterChainProxy - /api/mgt/appupdates at position 1 of 10 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
    2015-02-11 10:46:57,745 [http-nio-8080-exec-29] DEBUG org.springframework.security.web.FilterChainProxy - /api/mgt/appupdates at position 2 of 10 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
    2015-02-11 10:46:57,745 [http-nio-8080-exec-29] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
    2015-02-11 10:46:57,745 [http-nio-8080-exec-29] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.

I am using the Spring stack, including Spring 4.1.4.RELEASE, Spring Security 4, Spring Session 1.0.0.RELEASE, etc

Spring session config:

 @Configuration
 @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60 * 120 )
 public class RedisHttpSessionConfig {

    @Bean 
    public HttpSessionStrategy httpSessionStrategy(){
        return new HeaderHttpSessionStrategy(); 
    }

 }  

The Http Session initializer class content:

@Order(100)
public class RedisHttpSessionApplicationInitializer 
        extends AbstractHttpSessionApplicationInitializer {}

The RedisHttpSessionConfig is loaded in my web initializer(@Order(0)). And there is another Initializer for Spring Security(@Order(200)).

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {

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

    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {

        FilterRegistration.Dynamic corsFilter = servletContext.addFilter("corsFilter", DelegatingFilterProxy.class);
        corsFilter.addMappingForUrlPatterns(
                EnumSet.of(
                        DispatcherType.ERROR,
                        DispatcherType.REQUEST,
                        DispatcherType.FORWARD,
                        DispatcherType.INCLUDE,
                        DispatcherType.ASYNC),
                false,
                "/*"
        );

I have resolved the problem. I moved the doFilter method into a else block.

@Named("corsFilter")
public class SimpleCorsFilter extends OncePerRequestFilter {

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

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
            throws ServletException, IOException {
        if (log.isDebugEnabled()) {
            log.debug("call doFilter in SimpleCORSFilter @");
        }

        response.setHeader("Access-Control-Allow-Origin", "*");
 //       response.addHeader("X-FRAME-OPTIONS", "SAMEORIGIN");

        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {

            if (log.isDebugEnabled()) {
                log.debug("do pre flight...");
            }

            response.setHeader("Access-Control-Allow-Methods", "POST,GET,HEAD,OPTIONS,PUT,DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type,Accept,x-auth-token,x-xsrf-token,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Access-Control-Allow-Origin");
            //response.setHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin,x-auth-token");
        } else {
            filterChain.doFilter(request, response);
        }
    }

}

Thus the doFilter only executes in none OPTIONS method. This solution overcomes this barrier temporarily. I think this could be a Spring Session related bug.

2
You might want to add to filter about ignoring CROS. By default it blocks. Can you make sure you are hitting the filter.java_dude

2 Answers

0
votes

A CORS filter needs to know about the Spring Session header in the list of allowed request headers. HeaderHttpSessionStrategy defines this as "x-auth-token" but it can be changed. Note that any header starting with "x-" is treated as application specific, a tell-tale sign you need to configure your CORS filter to allow it.

0
votes

May it add a @CrossOrigin to your request method help? like below:

@GetMapping("/path")
    @CrossOrigin
    public String detail(@PathVariable("id") Integer activityId){


        return "";
    }