Reputation: 309
I'm trying to add an Authorization header to requests made using $http on the client side of my application.
I'm using nodejs to serve my client side app, and java with spring boot for my backend.
I've added the following filter to enable CORS:
public class CorsFilter extends GenericFilterBean {
private static final Logger logger = Logger.getLogger(CorsFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
logger.info("Enable cors filter");
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
res.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
chain.doFilter(request, response);
}
}
I'm setting an authorization header containing a token with the following line:
$http.defaults.headers.common.Authorization = 'Bearer ' + token;
yet angular seems to completely ignore this header, when checking the requests made in chrome I see:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:accept, access-control-expose-headers, authorization
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:3000
Pragma:no-cache
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
not trace if the authorization header.
I've added 'Authorization' to the Access-Control-Allow-Headers header in my response, the CORS seem to function properly, and I've set my CORS filter ass following:
@Bean
public FilterRegistrationBean corsFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new CorsFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registrationBean;
}
So it should occur first and on all URL patterns.
So what am I missing?
Upvotes: 0
Views: 1678
Reputation: 16641
The solution for the problem is in the comments, so I edited these in here:
The request you see in chrome is a CORS request for access. Method = OPTION. This is done by the browser not by angular. You CORSFilter should probably handle OPTION requests.
The problem was caused by a jwt filter that expected the authorization header, also on the OPTION request.
It was solved by adding a condition to only proceed with the jwt validation if the method is not OPTION.
Upvotes: 1