I am trying to write a custom filter, that checks for the user authentication using Spring 4.2. While making a request from the angular application, I get the following error:
Access to XMLHttpRequest from origin http://localhost:4200 has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
The header included in the angular Application is:
const requestHeaderObject = {
headers: request.headers
.append('Content-Type', 'application/json')
.append('Access-Control-Allow-Origin', '*')
.append('logged_user_id', 'userId')
.append('auth_token', 'authToken')
}
The code of my Filter in Spring is:
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// Fetching all the header params from request
HttpServletRequest httpRequest = (HttpServletRequest) request;
Enumeration<String> headerNames = httpRequest.getHeaderNames();
String loggedUserId = null;
String authToken = null;
if (headerNames != null) {
while (headerNames.nextElement() != null && headerNames.hasMoreElements()) {
loggedUserId = httpRequest.getHeader('logged_user_id');
authToken = httpRequest.getHeader('auth_token');
}
}
if (loggedUserId == null || authToken == null) {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
mapper.writeValue(response.getWriter(), getErrorDetailsMap());
return;
}
ApplicationContext appContext = AppContextConfig.getApplicationContext();
AccessManager accessManager = (AccessManager) appContext.getBean(AccessManager.class);
if(accessManager.isValidToken(loggedUserId, authToken) == false) {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
mapper.writeValue(response.getWriter(), getErrorDetailsMap());
return;
}
filterChain.doFilter(request, response);
}
I have done the following but was not successful:
Adding @CrossOrigin mapping to all the controllers
Adding the following code in my filter:
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");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
Disabling cors in the security configuration by overriding the configure method as follows:
http.cors().disable();Changed the headers in the angular applications.
Also I have tried to write another filter and passing the headers in that filter and calling it before my actual filter.