Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.iemr.common</groupId>
<artifactId>bengen-api</artifactId>
<version>3.4.0</version>
<version>3.6.0</version>
<packaging>war</packaging>

<name>BeneficiaryID-Generation-API</name>
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/com/iemr/common/bengen/config/CorsConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ public void addCorsMappings(CorsRegistry registry) {
Arrays.stream(allowedOrigins.split(","))
.map(String::trim)
.toArray(String[]::new))
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("Authorization", "Content-Type", "Accept", "Jwttoken",
"serverAuthorization", "ServerAuthorization", "serverauthorization", "Serverauthorization")
.exposedHeaders("Authorization", "Jwttoken")
.allowCredentials(true)
.maxAge(3600);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed for OPTIONS request");
return;
}
}
Comment on lines +83 to +90
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Dead code: OPTIONS case already handled above.

If origin is null and the method is OPTIONS, the request already returns at line 52. If origin is not allowed and the method is OPTIONS, the request already returns at line 57. Therefore, the condition at lines 86-89 is unreachable.

🧹 Remove dead code
         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)) {
-                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed for OPTIONS request");
-                return;
-            }
         }
🤖 Prompt for AI Agents
In @src/main/java/com/iemr/common/bengen/utils/JwtUserIdValidationFilter.java
around lines 83 - 90, The else branch in JwtUserIdValidationFilter that checks
for "OPTIONS" is dead code because OPTIONS is already handled earlier; remove
the inner if block that sends SC_FORBIDDEN for OPTIONS (the lines inside the
else that test "OPTIONS".equalsIgnoreCase(method) and call
response.sendError/return) and leave the else to only log the disallowed origin,
ensuring no duplicate OPTIONS handling remains in doFilterInternal (reference:
class JwtUserIdValidationFilter and its doFilterInternal method).

logger.info("JwtUserIdValidationFilter invoked for path: " + path);

// Log cookies for debugging
Expand Down Expand Up @@ -179,4 +213,13 @@ private void clearUserIdCookie(HttpServletResponse response) {
cookie.setMaxAge(0); // Invalidate the cookie
response.addCookie(cookie);
}

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");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@
*/
package com.iemr.common.bengen.utils.http;

import java.util.Arrays;

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;
Expand All @@ -43,6 +46,9 @@ public class HTTPRequestInterceptor implements HandlerInterceptor

Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

@Value("${cors.allowed-origins}")
private String allowedOrigins;

@Autowired
public void setValidator(Validator validator)
{
Expand Down Expand Up @@ -112,7 +118,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;
}

Expand Down Expand Up @@ -151,7 +163,23 @@ public void postHandle(
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object object, Exception arg3) throws Exception{
Object object, Exception arg3) throws Exception {
logger.debug("In afterCompletion Request Completed");
}

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);
});
}
}
Loading