Daniel G.
Daniel G.

Reputation: 124

Spring Security - Simple CORS authentication error

I have a spring based application using Spring Security to handle the authentication. Our application needs to provide support for simple Cross Origin Resource Sharing, the application can be accessed from 'http://myApplication.myDomain.net' and 'http://www.myApplication.myDomain.net', I've configured my Simple CORS Filter to allow multiple request origins,so these two domains will have the Access-Control-Allow-Origin request response header. The issue is that when I access the application from this domain 'http://myApplication.myDomain.net' is works perfectly, but when I try to access the application from here 'http://www.myApplication.myDomain.net' I'm only able to log in but the inmediate following request to display the main dash-board gets a 403 - Forbidden: Access is denied. I'm using AngularJS and grunt, from Angular all requests are made to http://myApplication.myDomain:8087/api/....

My question is, how can I add to support to both domains? Why the log ing request works but any further actions are forbiden?

Thanks.

Upvotes: 1

Views: 201

Answers (1)

kuhajeyan
kuhajeyan

Reputation: 11017

Add an interceptor

public class CorsInterceptor extends HandlerInterceptorAdapter {

 public static final String CREDENTIALS_NAME = "Access-Control-Allow-Credentials";
 public static final String ORIGIN_NAME = "Access-Control-Allow-Origin";
 public static final String METHODS_NAME = "Access-Control-Allow-Methods";
 public static final String HEADERS_NAME = "Access-Control-Allow-Headers";
 public static final String MAX_AGE_NAME = "Access-Control-Max-Age";
 public static final String REQUEST_ORIGIN_NAME = "Origin";

private final List<String> origins;

    public CorsInterceptor(List<String> origins) {
        this.origins = origins;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader(CREDENTIALS_NAME, "true");
        response.setHeader(METHODS_NAME, "GET, OPTIONS, POST, PUT, DELETE");
        response.setHeader(HEADERS_NAME, "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader(MAX_AGE_NAME, "3600");

        String origin = request.getHeader(REQUEST_ORIGIN_NAME);
        if (origins.contains(origin)) {
            response.setHeader(ORIGIN_NAME, origin);
            return true; // Proceed
        }

        return false;
   }

}

in Config

public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor(Arrays.asList("'http://myApplication.myDomain.net","http://www.myApplication.myDomain.net")));
    }

    ...

}

Upvotes: 1

Related Questions