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
5 changes: 3 additions & 2 deletions src/main/java/com/iemr/admin/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
77 changes: 59 additions & 18 deletions src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,23 +37,57 @@
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)) {

Check failure on line 48 in src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of duplicating this literal "OPTIONS" 3 times.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Admin-API&issues=AZrjl53jW5uRCu5lEfxy&open=AZrjl53jW5uRCu5lEfxy&pullRequest=112
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;
}
}

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

// Log cookies for debugging
Expand All @@ -70,7 +104,7 @@
}

// 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")
Expand Down Expand Up @@ -132,6 +166,15 @@
}
}

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");
Expand All @@ -144,14 +187,12 @@
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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);
});
}
}
Loading