Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Saturday, April 23, 2016

How to resolve CORS header after using Spring Security and Rest Service?


After testing an architecture of a security rest service built-in Spring Framework and a web application on AngularJS which over a POST gets credentials and regard information for the front end part, using firebug I discover and error after a submit on each event:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8081/keepnotes-soa-app/rest/user. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Reviewing on Internet I discovered a missing configuration over my Front-end application which is the result of having a separated application, so on I have to create the following lines:
package org.app.web.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
public class CORSFilter extends OncePerRequestFilter {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
LOGGER.debug("FILTO.CORS.INIT.0");
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
LOGGER.debug("FILTO.CORS.INIT.1");
LOGGER.trace("Sending Header....");
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
// response.addHeader("Access-Control-Allow-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Auth-Token");
response.addHeader("Access-Control-Max-Age", "1");
}
filterChain.doFilter(request, response);
}
}
view raw CORSFilter.java hosted with ❤ by GitHub
Having created the filter class we must to make the configuration over web.xml with the following lines:

...
<filter>
<filter-name>cors</filter-name>
<filter-class>org.app.web.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
view raw cors_web.xml hosted with ❤ by GitHub
Next to is review request and response where you were to find headers located on each message.

Best Regards,