Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CORS error for non-CORS requests #3329

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
HttpServletResponse httpResponse = WebUtils.toHttp(response);
HttpServletRequest httpRequest = WebUtils.toHttp(request);

int errorCode = httpResponse.getStatus();
if (errorCode >= 400) {
// if there's an error code at this point, return it and stop the chain
httpResponse.sendError(errorCode, null);
return;
}

String origin = httpRequest.getHeader(HttpHeaders.ORIGIN);
if (StringUtils.isEmpty(origin)) {
// Not a CORS request. Move along.
Expand All @@ -113,22 +120,17 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
// For the actual request it will be available and we will check the CORS according to the scope.
KapuaId scopeId = KapuaSecurityUtils.getSession() != null ? KapuaSecurityUtils.getSession().getScopeId() : null;

String msg = null;
if (checkOrigin(origin, scopeId)) {
// Origin matches at least one defined Endpoint
httpResponse.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
httpResponse.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
httpResponse.addHeader("Vary", HttpHeaders.ORIGIN);
} else {
msg = scopeId != null ?
String errorMessage = scopeId != null ?
String.format("HTTP Origin not allowed: %s for scope: %s", origin, scopeId.toCompactId()) :
String.format("HTTP Origin not allowed: %s", origin);
logger.error(msg);
}
int errorCode = httpResponse.getStatus();
if (errorCode >= 400) {
// if there's an error code at this point, return it and stop the chain
httpResponse.sendError(errorCode, msg);
logger.error(errorMessage);
httpResponse.sendError(errorCode, errorMessage);
return;
}
chain.doFilter(request, response);
Expand Down