-
Notifications
You must be signed in to change notification settings - Fork 32
fix: amm-1927 send headers only if the request is from the allowed origin #110
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -37,23 +37,57 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo | |
| HttpServletResponse response = (HttpServletResponse) servletResponse; | ||
|
|
||
| String origin = request.getHeader("Origin"); | ||
| if (origin != null && isOriginAllowed(origin)) { | ||
| response.setHeader("Access-Control-Allow-Origin", origin); | ||
| response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); | ||
| response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken"); | ||
| response.setHeader("Access-Control-Allow-Credentials", "true"); | ||
| String method = request.getMethod(); | ||
| String uri = request.getRequestURI(); | ||
|
|
||
| logger.debug("Incoming Origin: {}", origin); | ||
| logger.debug("Request Method: {}", method); | ||
| logger.debug("Request URI: {}", uri); | ||
| logger.debug("Allowed Origins Configured: {}", allowedOrigins); | ||
|
|
||
| if ("OPTIONS".equalsIgnoreCase(method)) { | ||
| if (origin == null) { | ||
| logger.warn("BLOCKED - OPTIONS request without Origin header | Method: {} | URI: {}", method, uri); | ||
| response.sendError(HttpServletResponse.SC_FORBIDDEN, "OPTIONS request requires Origin header"); | ||
| return; | ||
| } | ||
| if (!isOriginAllowed(origin)) { | ||
| logger.warn("BLOCKED - Unauthorized Origin | Origin: {} | Method: {} | URI: {}", origin, method, uri); | ||
| response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed"); | ||
| return; | ||
| } | ||
| } else { | ||
| logger.warn("Origin [{}] is NOT allowed. CORS headers NOT added.", origin); | ||
| } | ||
|
|
||
| if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { | ||
| logger.info("OPTIONS request - skipping JWT validation"); | ||
| response.setStatus(HttpServletResponse.SC_OK); | ||
| return; | ||
| // For non-OPTIONS requests, validate origin if present | ||
| if (origin != null && !isOriginAllowed(origin)) { | ||
| logger.warn("BLOCKED - Unauthorized Origin | Origin: {} | Method: {} | URI: {}", origin, method, uri); | ||
| response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed"); | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| // Determine request path/context for later checks | ||
| String path = request.getRequestURI(); | ||
| String contextPath = request.getContextPath(); | ||
|
|
||
| // Set CORS headers and handle OPTIONS request only if origin is valid and allowed | ||
| if (origin != null && isOriginAllowed(origin)) { | ||
| addCorsHeaders(response, origin); | ||
| logger.info("Origin Validated | Origin: {} | Method: {} | URI: {}", origin, method, uri); | ||
|
|
||
| if ("OPTIONS".equalsIgnoreCase(method)) { | ||
| // OPTIONS (preflight) - respond with full allowed methods | ||
| response.setStatus(HttpServletResponse.SC_OK); | ||
| return; | ||
| } | ||
| } else { | ||
| logger.warn("Origin [{}] is NOT allowed. CORS headers NOT added.", origin); | ||
|
|
||
| if ("OPTIONS".equalsIgnoreCase(method)) { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please check |
||
| response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed for OPTIONS request"); | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| logger.info("JwtUserIdValidationFilter invoked for path: " + path); | ||
|
|
||
| // Log cookies for debugging | ||
|
|
@@ -70,7 +104,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo | |
| } | ||
|
|
||
| // Log headers for debugging | ||
| logger.info("JWT token from header: "); | ||
| logger.debug("JWT token from header: {}", request.getHeader("Jwttoken") != null ? "present" : "not present"); | ||
|
|
||
| // Skip login and public endpoints | ||
| if (path.equals(contextPath + "/user/userAuthenticate") | ||
|
|
@@ -131,6 +165,15 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo | |
| } | ||
| } | ||
|
|
||
| private void addCorsHeaders(HttpServletResponse response, String origin) { | ||
| response.setHeader("Access-Control-Allow-Origin", origin); // Never use wildcard | ||
| response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS"); | ||
| response.setHeader("Access-Control-Allow-Headers", | ||
| "Authorization, Content-Type, Accept, Jwttoken, serverAuthorization, ServerAuthorization, serverauthorization, Serverauthorization"); | ||
| response.setHeader("Access-Control-Allow-Credentials", "true"); | ||
| response.setHeader("Access-Control-Max-Age", "3600"); | ||
| } | ||
|
|
||
| private boolean isOriginAllowed(String origin) { | ||
| if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) { | ||
| logger.warn("No allowed origins configured or origin is null"); | ||
|
|
@@ -143,14 +186,12 @@ private boolean isOriginAllowed(String origin) { | |
| String regex = pattern | ||
| .replace(".", "\\.") | ||
| .replace("*", ".*") | ||
| .replace("http://localhost:.*", "http://localhost:\\d+"); // special case for wildcard port | ||
|
|
||
| .replace("http://localhost:.*", "http://localhost:\\d+"); | ||
| boolean matched = origin.matches(regex); | ||
| return matched; | ||
| }); | ||
| } | ||
|
|
||
| private boolean isMobileClient(String userAgent) { | ||
| } private boolean isMobileClient(String userAgent) { | ||
| if (userAgent == null) | ||
| return false; | ||
| userAgent = userAgent.toLowerCase(); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,11 +22,14 @@ | |
| package com.iemr.admin.utils.http; | ||
|
|
||
|
|
||
| import java.util.Arrays; | ||
|
|
||
| import javax.ws.rs.core.MediaType; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.servlet.HandlerInterceptor; | ||
| import org.springframework.web.servlet.ModelAndView; | ||
|
|
@@ -41,6 +44,8 @@ | |
| @Component | ||
| public class HTTPRequestInterceptor implements HandlerInterceptor { | ||
| Logger logger = LoggerFactory.getLogger(this.getClass().getName()); | ||
| @Value("${cors.allowed-origins}") | ||
| private String allowedOrigins; | ||
| @Autowired | ||
| private RedisStorage redisStorage; | ||
| @Autowired | ||
|
|
@@ -104,7 +109,13 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons | |
| response.getOutputStream().print(output.toString()); | ||
| response.setContentType(MediaType.APPLICATION_JSON); | ||
| response.setContentLength(output.toString().length()); | ||
| response.setHeader("Access-Control-Allow-Origin", "*"); | ||
| String origin = request.getHeader("Origin"); | ||
| if (origin != null && isOriginAllowed(origin)) { | ||
| response.setHeader("Access-Control-Allow-Origin", origin); | ||
| response.setHeader("Access-Control-Allow-Credentials", "true"); | ||
| } else if (origin != null) { | ||
| logger.warn("CORS headers NOT added for error response | Unauthorized origin: {}", origin); | ||
| } | ||
| status = false; | ||
| } | ||
| } | ||
|
|
@@ -138,4 +149,20 @@ public void afterCompletion(HttpServletRequest request, HttpServletResponse resp | |
| logger.info("http interceptor - after completion"); | ||
|
|
||
| } | ||
|
|
||
| private boolean isOriginAllowed(String origin) { | ||
| if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) { | ||
| return false; | ||
| } | ||
|
|
||
| return Arrays.stream(allowedOrigins.split(",")) | ||
| .map(String::trim) | ||
| .anyMatch(pattern -> { | ||
| String regex = pattern | ||
| .replace(".", "\\.") | ||
| .replace("*", ".*") | ||
| .replace("http://localhost:.*", "http://localhost:\\d+"); | ||
| return origin.matches(regex); | ||
| }); | ||
| } | ||
|
Comment on lines
153
to
167
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. π οΈ Refactor suggestion | π Major Code duplication: isOriginAllowed method. This method duplicates identical logic found in JwtUserIdValidationFilter (lines 172-188). Code duplication creates maintenance overhead and risks inconsistencies when one copy is updated but not the other. Extract this method to a shared utility class that both HTTPRequestInterceptor and JwtUserIdValidationFilter can use: // New file: src/main/java/com/iemr/admin/utils/CorsOriginValidator.java
package com.iemr.admin.utils;
import java.util.Arrays;
import org.springframework.stereotype.Component;
@Component
public class CorsOriginValidator {
public boolean isOriginAllowed(String origin, String allowedOrigins) {
if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
return false;
}
return Arrays.stream(allowedOrigins.split(","))
.map(String::trim)
.anyMatch(pattern -> {
String regex = pattern
.replace(".", "\\.")
.replace("*", ".*");
return origin.matches(regex);
});
}
}Then inject and use this utility in both classes. π€ Prompt for AI Agents
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. tolerable due to ease of readability There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @5Amogh, understood! I've noted your preference. The duplicated method is indeed small and self-contained, so keeping it local to each class can make the code easier to follow without jumping between files. βοΈ Learnings added
|
||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@5Amogh The current implementation returns 200 OK for OPTIONS requests, which is the correct behavior for CORS preflight requests. Could you please check it and revert back to the original implementation? As per my understanding, if we return 403 for invalid origins, the browser displays a confusing error message. When we return 200 OK without CORS headers, the browser shows a clear and correct message: βCORS policy: No βAccess-Control-Allow-Originβ header is present